VLCPlaybackController.m 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  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 <MediaPlayer/MediaPlayer.h>
  23. #import "VLCThumbnailsCache.h"
  24. #import <WatchKit/WatchKit.h>
  25. #import "VLCPlaylistViewController.h"
  26. #import "VLCKeychainCoordinator.h"
  27. NSString *const VLCPlaybackControllerPlaybackDidStart = @"VLCPlaybackControllerPlaybackDidStart";
  28. NSString *const VLCPlaybackControllerPlaybackDidPause = @"VLCPlaybackControllerPlaybackDidPause";
  29. NSString *const VLCPlaybackControllerPlaybackDidResume = @"VLCPlaybackControllerPlaybackDidResume";
  30. NSString *const VLCPlaybackControllerPlaybackDidStop = @"VLCPlaybackControllerPlaybackDidStop";
  31. NSString *const VLCPlaybackControllerPlaybackMetadataDidChange = @"VLCPlaybackControllerPlaybackMetadataDidChange";
  32. NSString *const VLCPlaybackControllerPlaybackDidFail = @"VLCPlaybackControllerPlaybackDidFail";
  33. @interface VLCPlaybackController () <AVAudioSessionDelegate, VLCMediaPlayerDelegate, VLCMediaDelegate>
  34. {
  35. BOOL _playerIsSetup;
  36. BOOL _playbackFailed;
  37. BOOL _shouldResumePlaying;
  38. BOOL _shouldResumePlayingAfterInteruption;
  39. NSTimer *_sleepTimer;
  40. NSArray *_aspectRatios;
  41. NSUInteger _currentAspectRatioMask;
  42. float _currentPlaybackRate;
  43. UIView *_videoOutputViewWrapper;
  44. UIView *_actualVideoOutputView;
  45. UIView *_preBackgroundWrapperView;
  46. /* cached stuff for the VC */
  47. NSString *_title;
  48. UIImage *_artworkImage;
  49. NSString *_artist;
  50. NSString *_albumName;
  51. BOOL _mediaIsAudioOnly;
  52. BOOL _needsMetadataUpdate;
  53. BOOL _mediaWasJustStarted;
  54. BOOL _recheckForExistingThumbnail;
  55. BOOL _activeSession;
  56. }
  57. @end
  58. @implementation VLCPlaybackController
  59. #pragma mark instance management
  60. + (VLCPlaybackController *)sharedInstance
  61. {
  62. static VLCPlaybackController *sharedInstance = nil;
  63. static dispatch_once_t pred;
  64. dispatch_once(&pred, ^{
  65. sharedInstance = [VLCPlaybackController new];
  66. });
  67. return sharedInstance;
  68. }
  69. - (void)dealloc
  70. {
  71. [[NSNotificationCenter defaultCenter] removeObserver:self];
  72. }
  73. #pragma mark - playback management
  74. - (BOOL)_blobCheck
  75. {
  76. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  77. NSString *directoryPath = searchPaths[0];
  78. if (![[NSFileManager defaultManager] fileExistsAtPath:[directoryPath stringByAppendingPathComponent:@"blob.bin"]])
  79. return NO;
  80. NSData *data = [NSData dataWithContentsOfFile:[directoryPath stringByAppendingPathComponent:@"blob.bin"]];
  81. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  82. CC_SHA1(data.bytes, (unsigned int)data.length, digest);
  83. NSMutableString *hash = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  84. for (unsigned int u = 0; u < CC_SHA1_DIGEST_LENGTH; u++)
  85. [hash appendFormat:@"%02x", digest[u]];
  86. if ([hash isEqualToString:kBlobHash])
  87. return YES;
  88. else
  89. return NO;
  90. }
  91. - (BOOL)_isMediaSuitableForDevice:(VLCMedia *)media
  92. {
  93. NSArray *tracksInfo = media.tracksInformation;
  94. double width, height = 0;
  95. NSDictionary *track;
  96. for (NSUInteger x = 0; x < tracksInfo.count; x++) {
  97. track = tracksInfo[x];
  98. if ([track[VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  99. width = [track[VLCMediaTracksInformationVideoWidth] doubleValue];
  100. height = [track[VLCMediaTracksInformationVideoHeight] doubleValue];
  101. }
  102. }
  103. NSUInteger totalNumberOfPixels = width * height;
  104. NSInteger speedCategory = [[UIDevice currentDevice] speedCategory];
  105. if (speedCategory == 1) {
  106. // iPhone 3GS, iPhone 4, first gen. iPad, 3rd and 4th generation iPod touch
  107. return (totalNumberOfPixels < 600000); // between 480p and 720p
  108. } else if (speedCategory == 2) {
  109. // iPhone 4S, iPad 2 and 3, iPod 4 and 5
  110. return (totalNumberOfPixels < 922000); // 720p
  111. } else if (speedCategory == 3) {
  112. // iPhone 5, iPad 4
  113. return (totalNumberOfPixels < 2074000); // 1080p
  114. } else if (speedCategory == 4) {
  115. // iPhone 6, 2014 iPads
  116. return (totalNumberOfPixels < 8850000); // 4K
  117. }
  118. return YES;
  119. }
  120. - (void)startPlayback
  121. {
  122. if (_playerIsSetup)
  123. return;
  124. _activeSession = YES;
  125. [[AVAudioSession sharedInstance] setDelegate:self];
  126. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  127. [defaultCenter addObserver:self selector:@selector(audioSessionRouteChange:)
  128. name:AVAudioSessionRouteChangeNotification object:nil];
  129. [defaultCenter addObserver:self selector:@selector(applicationWillResignActive:)
  130. name:UIApplicationWillResignActiveNotification object:nil];
  131. [defaultCenter addObserver:self selector:@selector(applicationDidBecomeActive:)
  132. name:UIApplicationDidBecomeActiveNotification object:nil];
  133. [defaultCenter addObserver:self selector:@selector(applicationDidEnterBackground:)
  134. name:UIApplicationDidEnterBackgroundNotification object:nil];
  135. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  136. _aspectRatios = @[@"DEFAULT", @"FILL_TO_SCREEN", @"4:3", @"16:9", @"16:10", @"2.21:1"];
  137. if (!self.url && !self.mediaList) {
  138. [self stopPlayback];
  139. return;
  140. }
  141. if (self.pathToExternalSubtitlesFile)
  142. _listPlayer = [[VLCMediaListPlayer alloc] initWithOptions:@[[NSString stringWithFormat:@"--%@=%@", kVLCSettingSubtitlesFilePath, self.pathToExternalSubtitlesFile]]];
  143. else
  144. _listPlayer = [[VLCMediaListPlayer alloc] init];
  145. /* video decoding permanently fails if we don't provide a UIView to draw into on init
  146. * hence we provide one which is not attached to any view controller for off-screen drawing
  147. * and disable video decoding once playback started */
  148. _actualVideoOutputView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
  149. _actualVideoOutputView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  150. _actualVideoOutputView.autoresizesSubviews = YES;
  151. _mediaPlayer = _listPlayer.mediaPlayer;
  152. [_mediaPlayer setDelegate:self];
  153. [_mediaPlayer setDrawable:_actualVideoOutputView];
  154. if ([[defaults objectForKey:kVLCSettingPlaybackSpeedDefaultValue] floatValue] != 0)
  155. [_mediaPlayer setRate: [[defaults objectForKey:kVLCSettingPlaybackSpeedDefaultValue] floatValue]];
  156. if ([[defaults objectForKey:kVLCSettingDeinterlace] intValue] != 0)
  157. [_mediaPlayer setDeinterlaceFilter:@"blend"];
  158. else
  159. [_mediaPlayer setDeinterlaceFilter:nil];
  160. if (self.pathToExternalSubtitlesFile)
  161. [_mediaPlayer openVideoSubTitlesFromFile:self.pathToExternalSubtitlesFile];
  162. VLCMedia *media;
  163. if (_mediaList) {
  164. media = [_mediaList mediaAtIndex:_itemInMediaListToBePlayedFirst];
  165. media.delegate = self;
  166. } else {
  167. media = [VLCMedia mediaWithURL:self.url];
  168. media.delegate = self;
  169. [media synchronousParse];
  170. }
  171. NSMutableDictionary *mediaDictionary = [[NSMutableDictionary alloc] init];
  172. [mediaDictionary setObject:[defaults objectForKey:kVLCSettingNetworkCaching] forKey:kVLCSettingNetworkCaching];
  173. [mediaDictionary setObject:[[defaults objectForKey:kVLCSettingStretchAudio] boolValue] ? kVLCSettingStretchAudioOnValue : kVLCSettingStretchAudioOffValue forKey:kVLCSettingStretchAudio];
  174. [mediaDictionary setObject:[defaults objectForKey:kVLCSettingTextEncoding] forKey:kVLCSettingTextEncoding];
  175. [mediaDictionary setObject:[defaults objectForKey:kVLCSettingSkipLoopFilter] forKey:kVLCSettingSkipLoopFilter];
  176. #if 0
  177. [NSTimeZone resetSystemTimeZone];
  178. NSString *tzName = [[NSTimeZone systemTimeZone] name];
  179. NSArray *tzNames = @[@"America/Adak", @"America/Anchorage", @"America/Boise", @"America/Chicago", @"America/Denver", @"America/Detroit", @"America/Indiana/Indianapolis", @"America/Indiana/Knox", @"America/Indiana/Marengo", @"America/Indiana/Petersburg", @"America/Indiana/Tell_City", @"America/Indiana/Vevay", @"America/Indiana/Vincennes", @"America/Indiana/Winamac", @"America/Juneau", @"America/Kentucky/Louisville", @"America/Kentucky/Monticello", @"America/Los_Angeles", @"America/Menominee", @"America/Metlakatla", @"America/New_York", @"America/Nome", @"America/North_Dakota/Beulah", @"America/North_Dakota/Center", @"America/North_Dakota/New_Salem", @"America/Phoenix", @"America/Puerto_Rico", @"America/Shiprock", @"America/Sitka", @"America/St_Thomas", @"America/Thule", @"America/Yakutat", @"Pacific/Guam", @"Pacific/Honolulu", @"Pacific/Johnston", @"Pacific/Kwajalein", @"Pacific/Midway", @"Pacific/Pago_Pago", @"Pacific/Saipan", @"Pacific/Wake"];
  180. if ([tzNames containsObject:tzName] || [[tzName stringByDeletingLastPathComponent] isEqualToString:@"US"]) {
  181. NSArray *tracksInfo = media.tracksInformation;
  182. for (NSUInteger x = 0; x < tracksInfo.count; x++) {
  183. if ([[tracksInfo[x] objectForKey:VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeAudio])
  184. {
  185. NSInteger fourcc = [[tracksInfo[x] objectForKey:VLCMediaTracksInformationCodec] integerValue];
  186. switch (fourcc) {
  187. case 540161377:
  188. case 1647457633:
  189. case 858612577:
  190. case 862151027:
  191. case 862151013:
  192. case 1684566644:
  193. case 2126701:
  194. {
  195. if (![self _blobCheck]) {
  196. [mediaDictionary setObject:[NSNull null] forKey:@"no-audio"];
  197. APLog(@"audio playback disabled because an unsupported codec was found");
  198. }
  199. break;
  200. }
  201. default:
  202. break;
  203. }
  204. }
  205. }
  206. }
  207. #endif
  208. if (self.mediaList) {
  209. VLCMediaList *list = self.mediaList;
  210. NSUInteger count = list.count;
  211. for (NSUInteger x = 0; x < count; x++)
  212. [[list mediaAtIndex:x] addOptions:mediaDictionary];
  213. [_listPlayer setMediaList:self.mediaList];
  214. } else {
  215. [media addOptions:mediaDictionary];
  216. [_listPlayer setRootMedia:media];
  217. }
  218. [_listPlayer setRepeatMode:VLCDoNotRepeat];
  219. if (![self _isMediaSuitableForDevice:media]) {
  220. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DEVICE_TOOSLOW_TITLE", nil)
  221. message:[NSString stringWithFormat:NSLocalizedString(@"DEVICE_TOOSLOW", nil), [[UIDevice currentDevice] model], media.url.lastPathComponent]
  222. delegate:self
  223. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  224. otherButtonTitles:NSLocalizedString(@"BUTTON_OPEN", nil), nil];
  225. [alert show];
  226. } else
  227. [self _playNewMedia];
  228. }
  229. - (void)_playNewMedia
  230. {
  231. // Set last selected equalizer profile
  232. unsigned int profile = (unsigned int)[[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingEqualizerProfile] integerValue];
  233. [_mediaPlayer resetEqualizerFromProfile:profile];
  234. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  235. _mediaWasJustStarted = YES;
  236. [_mediaPlayer addObserver:self forKeyPath:@"time" options:0 context:nil];
  237. [_mediaPlayer addObserver:self forKeyPath:@"remainingTime" options:0 context:nil];
  238. if (self.mediaList)
  239. [_listPlayer playItemAtIndex:self.itemInMediaListToBePlayedFirst];
  240. else
  241. [_listPlayer playMedia:_listPlayer.rootMedia];
  242. if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  243. [self.delegate prepareForMediaPlayback:self];
  244. _currentAspectRatioMask = 0;
  245. _mediaPlayer.videoAspectRatio = NULL;
  246. [self subscribeRemoteCommands];
  247. _playerIsSetup = YES;
  248. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidStart object:self];
  249. }
  250. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  251. {
  252. if (buttonIndex == 1)
  253. [self _playNewMedia];
  254. else
  255. [self stopPlayback];
  256. }
  257. - (void)stopPlayback
  258. {
  259. if (_mediaPlayer) {
  260. @try {
  261. [_mediaPlayer removeObserver:self forKeyPath:@"time"];
  262. [_mediaPlayer removeObserver:self forKeyPath:@"remainingTime"];
  263. }
  264. @catch (NSException *exception) {
  265. APLog(@"we weren't an observer yet");
  266. }
  267. if (_mediaPlayer.media) {
  268. [_mediaPlayer pause];
  269. [self _savePlaybackState];
  270. [_mediaPlayer stop];
  271. }
  272. if (_mediaPlayer)
  273. _mediaPlayer = nil;
  274. if (_listPlayer)
  275. _listPlayer = nil;
  276. }
  277. if (_mediaList)
  278. _mediaList = nil;
  279. if (_url)
  280. _url = nil;
  281. if (_pathToExternalSubtitlesFile) {
  282. NSFileManager *fileManager = [NSFileManager defaultManager];
  283. if ([fileManager fileExistsAtPath:_pathToExternalSubtitlesFile])
  284. [fileManager removeItemAtPath:_pathToExternalSubtitlesFile error:nil];
  285. _pathToExternalSubtitlesFile = nil;
  286. }
  287. _playerIsSetup = NO;
  288. if (self.errorCallback && _playbackFailed)
  289. [[UIApplication sharedApplication] openURL:self.errorCallback];
  290. else if (self.successCallback)
  291. [[UIApplication sharedApplication] openURL:self.successCallback];
  292. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = nil;
  293. [self unsubscribeFromRemoteCommand];
  294. _activeSession = NO;
  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. - (void)_savePlaybackState
  305. {
  306. MLFile *fileItem;
  307. NSArray *files = [MLFile fileForURL:_mediaPlayer.media.url];
  308. if (files.count > 0)
  309. fileItem = files.firstObject;
  310. if (!fileItem)
  311. return;
  312. @try {
  313. float position = _mediaPlayer.position;
  314. fileItem.lastPosition = @(position);
  315. fileItem.lastAudioTrack = @(_mediaPlayer.currentAudioTrackIndex);
  316. fileItem.lastSubtitleTrack = @(_mediaPlayer.currentVideoSubTitleIndex);
  317. if ([fileItem isKindOfType:kMLFileTypeAudio])
  318. return;
  319. if (position > .95)
  320. return;
  321. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  322. NSString* newThumbnailPath = [searchPaths[0] stringByAppendingPathComponent:@"VideoSnapshots"];
  323. NSFileManager *fileManager = [NSFileManager defaultManager];
  324. if (![fileManager fileExistsAtPath:newThumbnailPath])
  325. [fileManager createDirectoryAtPath:newThumbnailPath withIntermediateDirectories:YES attributes:nil error:nil];
  326. newThumbnailPath = [newThumbnailPath stringByAppendingPathComponent:fileItem.objectID.URIRepresentation.lastPathComponent];
  327. [_mediaPlayer saveVideoSnapshotAt:newThumbnailPath withWidth:0 andHeight:0];
  328. _recheckForExistingThumbnail = YES;
  329. [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:.25];
  330. }
  331. @catch (NSException *exception) {
  332. APLog(@"failed to save current media state - file removed?");
  333. }
  334. }
  335. - (void)_updateStoredThumbnailForFile:(MLFile *)fileItem
  336. {
  337. NSFileManager *fileManager = [NSFileManager defaultManager];
  338. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  339. NSString* newThumbnailPath = [searchPaths[0] stringByAppendingPathComponent:@"VideoSnapshots"];
  340. newThumbnailPath = [newThumbnailPath stringByAppendingPathComponent:fileItem.objectID.URIRepresentation.lastPathComponent];
  341. if (![fileManager fileExistsAtPath:newThumbnailPath]) {
  342. if (_recheckForExistingThumbnail) {
  343. [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:1.];
  344. _recheckForExistingThumbnail = NO;
  345. } else
  346. return;
  347. }
  348. UIImage *newThumbnail = [UIImage imageWithContentsOfFile:newThumbnailPath];
  349. if (!newThumbnail) {
  350. if (_recheckForExistingThumbnail) {
  351. [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:1.];
  352. _recheckForExistingThumbnail = NO;
  353. } else
  354. return;
  355. }
  356. @try {
  357. [fileItem setComputedThumbnailScaledForDevice:newThumbnail];
  358. }
  359. @catch (NSException *exception) {
  360. APLog(@"updating thumbnail failed");
  361. }
  362. [fileManager removeItemAtPath:newThumbnailPath error:nil];
  363. }
  364. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
  365. {
  366. if (_mediaWasJustStarted) {
  367. _mediaWasJustStarted = NO;
  368. if (self.mediaList) {
  369. MLFile *item;
  370. NSArray *matches = [MLFile fileForURL:_mediaPlayer.media.url];
  371. item = matches.firstObject;
  372. [self _recoverLastPlaybackStateOfItem:item];
  373. }
  374. }
  375. if ([self.delegate respondsToSelector:@selector(playbackPositionUpdated:)])
  376. [self.delegate playbackPositionUpdated:self];
  377. }
  378. - (NSInteger)mediaDuration
  379. {
  380. return _listPlayer.mediaPlayer.media.length.intValue;;
  381. }
  382. - (BOOL)isPlaying
  383. {
  384. return _mediaPlayer.isPlaying;
  385. }
  386. - (VLCRepeatMode)repeatMode
  387. {
  388. return _listPlayer.repeatMode;
  389. }
  390. - (void)setRepeatMode:(VLCRepeatMode)repeatMode
  391. {
  392. _listPlayer.repeatMode = repeatMode;
  393. }
  394. - (BOOL)currentMediaHasChapters
  395. {
  396. return [_mediaPlayer countOfTitles] > 1 || [_mediaPlayer chaptersForTitleIndex:_mediaPlayer.currentTitleIndex].count > 1;
  397. }
  398. - (BOOL)currentMediaHasTrackToChooseFrom
  399. {
  400. return [[_mediaPlayer audioTrackIndexes] count] > 2 || [[_mediaPlayer videoSubTitlesIndexes] count] > 1;
  401. }
  402. - (BOOL)activePlaybackSession
  403. {
  404. return _activeSession;
  405. }
  406. - (BOOL)audioOnlyPlaybackSession
  407. {
  408. return _mediaIsAudioOnly;
  409. }
  410. - (float)playbackRate
  411. {
  412. float f_rate = _mediaPlayer.rate;
  413. _currentPlaybackRate = f_rate;
  414. return f_rate;
  415. }
  416. - (void)setPlaybackRate:(float)playbackRate
  417. {
  418. if (_currentPlaybackRate != playbackRate)
  419. [_mediaPlayer setRate:playbackRate];
  420. _currentPlaybackRate = playbackRate;
  421. }
  422. - (void)setAudioDelay:(float)audioDelay
  423. {
  424. _mediaPlayer.currentAudioPlaybackDelay = 1000000.*audioDelay;
  425. }
  426. - (float)audioDelay
  427. {
  428. return _mediaPlayer.currentAudioPlaybackDelay/1000000.;
  429. }
  430. -(void)setSubtitleDelay:(float)subtitleDeleay
  431. {
  432. _mediaPlayer.currentVideoSubTitleDelay = 1000000.*subtitleDeleay;
  433. }
  434. - (float)subtitleDelay
  435. {
  436. return _mediaPlayer.currentVideoSubTitleDelay/1000000.;
  437. }
  438. - (void)mediaPlayerStateChanged:(NSNotification *)aNotification
  439. {
  440. VLCMediaPlayerState currentState = _mediaPlayer.state;
  441. if (currentState == VLCMediaPlayerStateBuffering) {
  442. /* attach delegate */
  443. _mediaPlayer.media.delegate = self;
  444. /* on-the-fly values through hidden API */
  445. [_mediaPlayer performSelector:@selector(setTextRendererFont:) withObject:[self _resolveFontName]];
  446. [_mediaPlayer performSelector:@selector(setTextRendererFontSize:) withObject:[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingSubtitlesFontSize]];
  447. [_mediaPlayer performSelector:@selector(setTextRendererFontColor:) withObject:[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingSubtitlesFontColor]];
  448. } else if (currentState == VLCMediaPlayerStateError) {
  449. _playbackFailed = YES;
  450. [self stopPlayback];
  451. } else if ((currentState == VLCMediaPlayerStateEnded || currentState == VLCMediaPlayerStateStopped) && _listPlayer.repeatMode == VLCDoNotRepeat) {
  452. if ([_listPlayer.mediaList indexOfMedia:_mediaPlayer.media] == _listPlayer.mediaList.count - 1) {
  453. [self stopPlayback];
  454. return;
  455. }
  456. }
  457. /* disable video decoding if we have no place to show */
  458. if (_mediaPlayer.numberOfAudioTracks > 0) {
  459. if (_videoOutputViewWrapper == nil)
  460. _mediaPlayer.currentVideoTrackIndex = -1;
  461. }
  462. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  463. [self.delegate mediaPlayerStateChanged:currentState
  464. isPlaying:_mediaPlayer.isPlaying
  465. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  466. currentMediaHasChapters:self.currentMediaHasChapters
  467. forPlaybackController:self];
  468. [self setNeedsMetadataUpdate];
  469. }
  470. #pragma mark - playback controls
  471. - (void)playPause
  472. {
  473. if ([_mediaPlayer isPlaying]) {
  474. [_listPlayer pause];
  475. [self _savePlaybackState];
  476. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
  477. } else {
  478. [_listPlayer play];
  479. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidResume object:self];
  480. }
  481. }
  482. - (void)forward
  483. {
  484. if (_mediaList) {
  485. [_listPlayer next];
  486. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  487. } else {
  488. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackForwardSkipLength];
  489. [_mediaPlayer jumpForward:skipLength.intValue];
  490. }
  491. }
  492. - (void)backward
  493. {
  494. if (_mediaList) {
  495. [_listPlayer previous];
  496. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  497. }
  498. else {
  499. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  500. [_mediaPlayer jumpBackward:skipLength.intValue];
  501. }
  502. }
  503. - (void)switchAspectRatio
  504. {
  505. NSUInteger count = [_aspectRatios count];
  506. if (_currentAspectRatioMask + 1 > count - 1) {
  507. _mediaPlayer.videoAspectRatio = NULL;
  508. _mediaPlayer.videoCropGeometry = NULL;
  509. _currentAspectRatioMask = 0;
  510. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  511. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), NSLocalizedString(@"DEFAULT", nil)] forPlaybackController:self];
  512. } else {
  513. _currentAspectRatioMask++;
  514. if ([_aspectRatios[_currentAspectRatioMask] isEqualToString:@"FILL_TO_SCREEN"]) {
  515. UIScreen *screen;
  516. if (![[UIDevice currentDevice] hasExternalDisplay])
  517. screen = [UIScreen mainScreen];
  518. else
  519. screen = [UIScreen screens][1];
  520. float f_ar = screen.bounds.size.width / screen.bounds.size.height;
  521. if (f_ar == (float)(640./1136.)) // iPhone 5 aka 16:9.01
  522. _mediaPlayer.videoCropGeometry = "16:9";
  523. else if (f_ar == (float)(2./3.)) // all other iPhones
  524. _mediaPlayer.videoCropGeometry = "16:10"; // libvlc doesn't support 2:3 crop
  525. else if (f_ar == (float)(1. + (1./3.))) // all iPads
  526. _mediaPlayer.videoCropGeometry = "4:3";
  527. else if (f_ar == .5625) // AirPlay
  528. _mediaPlayer.videoCropGeometry = "16:9";
  529. else
  530. APLog(@"unknown screen format %f, can't crop", f_ar);
  531. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  532. [self.delegate showStatusMessage:NSLocalizedString(@"FILL_TO_SCREEN", nil) forPlaybackController:self];
  533. return;
  534. }
  535. _mediaPlayer.videoCropGeometry = NULL;
  536. _mediaPlayer.videoAspectRatio = (char *)[_aspectRatios[_currentAspectRatioMask] UTF8String];
  537. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  538. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), _aspectRatios[_currentAspectRatioMask]] forPlaybackController:self];
  539. }
  540. }
  541. - (void)setVideoOutputView:(UIView *)videoOutputView
  542. {
  543. if (videoOutputView) {
  544. if ([_actualVideoOutputView superview] != nil)
  545. [_actualVideoOutputView removeFromSuperview];
  546. _actualVideoOutputView.frame = (CGRect){CGPointZero, videoOutputView.frame.size};
  547. [_actualVideoOutputView layoutSubviews];
  548. [_actualVideoOutputView updateConstraints];
  549. if (_mediaPlayer.currentVideoTrackIndex == -1)
  550. _mediaPlayer.currentVideoTrackIndex = 0;
  551. [videoOutputView addSubview:_actualVideoOutputView];
  552. } else
  553. [_actualVideoOutputView removeFromSuperview];
  554. _videoOutputViewWrapper = videoOutputView;
  555. }
  556. - (UIView *)videoOutputView
  557. {
  558. return _videoOutputViewWrapper;
  559. }
  560. #pragma mark - equalizer
  561. - (void)setAmplification:(CGFloat)amplification forBand:(unsigned int)index
  562. {
  563. if (!_mediaPlayer.equalizerEnabled)
  564. [_mediaPlayer setEqualizerEnabled:YES];
  565. [_mediaPlayer setAmplification:amplification forBand:index];
  566. // For some reason we have to apply again preamp to apply change
  567. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  568. }
  569. - (CGFloat)amplificationOfBand:(unsigned int)index
  570. {
  571. return [_mediaPlayer amplificationOfBand:index];
  572. }
  573. - (NSArray *)equalizerProfiles
  574. {
  575. return _mediaPlayer.equalizerProfiles;
  576. }
  577. - (void)resetEqualizerFromProfile:(unsigned int)profile
  578. {
  579. [[NSUserDefaults standardUserDefaults] setObject:@(profile) forKey:kVLCSettingEqualizerProfile];
  580. [_mediaPlayer resetEqualizerFromProfile:profile];
  581. }
  582. - (void)setPreAmplification:(CGFloat)preAmplification
  583. {
  584. if (!_mediaPlayer.equalizerEnabled)
  585. [_mediaPlayer setEqualizerEnabled:YES];
  586. [_mediaPlayer setPreAmplification:preAmplification];
  587. }
  588. - (CGFloat)preAmplification
  589. {
  590. return [_mediaPlayer preAmplification];
  591. }
  592. #pragma mark - AVSession delegate
  593. - (void)beginInterruption
  594. {
  595. if ([_mediaPlayer isPlaying]) {
  596. [_mediaPlayer pause];
  597. _shouldResumePlayingAfterInteruption = YES;
  598. }
  599. }
  600. - (void)endInterruption
  601. {
  602. if (_shouldResumePlayingAfterInteruption) {
  603. [_mediaPlayer play];
  604. _shouldResumePlayingAfterInteruption = NO;
  605. }
  606. }
  607. - (void)audioSessionRouteChange:(NSNotification *)notification
  608. {
  609. NSArray *outputs = [[AVAudioSession sharedInstance] currentRoute].outputs;
  610. NSString *portName = [[outputs firstObject] portName];
  611. if (![portName isEqualToString:@"Headphones"] && [_mediaPlayer isPlaying]) {
  612. [_mediaPlayer pause];
  613. [self _savePlaybackState];
  614. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
  615. }
  616. }
  617. #pragma mark - Managing the media item
  618. - (void)setUrl:(NSURL *)url
  619. {
  620. [self stopPlayback];
  621. _url = url;
  622. _playerIsSetup = NO;
  623. }
  624. - (void)setMediaList:(VLCMediaList *)mediaList
  625. {
  626. [self stopPlayback];
  627. _mediaList = mediaList;
  628. _playerIsSetup = NO;
  629. }
  630. - (MLFile *)currentlyPlayingMediaFile {
  631. if (self.mediaList) {
  632. NSArray *results = [MLFile fileForURL:_mediaPlayer.media.url];
  633. return results.firstObject;
  634. }
  635. return nil;
  636. }
  637. #pragma mark - metadata handling
  638. - (void)mediaDidFinishParsing:(VLCMedia *)aMedia
  639. {
  640. [self setNeedsMetadataUpdate];
  641. }
  642. - (void)mediaMetaDataDidChange:(VLCMedia*)aMedia
  643. {
  644. [self setNeedsMetadataUpdate];
  645. }
  646. - (void)setNeedsMetadataUpdate
  647. {
  648. if (_needsMetadataUpdate == NO) {
  649. _needsMetadataUpdate = YES;
  650. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  651. [self _updateDisplayedMetadata];
  652. });
  653. }
  654. }
  655. - (void)_updateDisplayedMetadata
  656. {
  657. _needsMetadataUpdate = NO;
  658. MLFile *item;
  659. NSNumber *trackNumber;
  660. NSString *title;
  661. NSString *artist;
  662. NSString *albumName;
  663. UIImage* artworkImage;
  664. BOOL mediaIsAudioOnly = NO;
  665. if (self.mediaList) {
  666. NSArray *matches = [MLFile fileForURL:_mediaPlayer.media.url];
  667. item = matches.firstObject;
  668. }
  669. if (item) {
  670. if (item.isAlbumTrack) {
  671. title = item.albumTrack.title;
  672. artist = item.albumTrack.artist;
  673. albumName = item.albumTrack.album.name;
  674. } else
  675. title = item.title;
  676. /* MLKit knows better than us if this thing is audio only or not */
  677. mediaIsAudioOnly = [item isSupportedAudioFile];
  678. } else {
  679. NSDictionary * metaDict = _mediaPlayer.media.metaDictionary;
  680. if (metaDict) {
  681. title = metaDict[VLCMetaInformationNowPlaying] ? metaDict[VLCMetaInformationNowPlaying] : metaDict[VLCMetaInformationTitle];
  682. artist = metaDict[VLCMetaInformationArtist];
  683. albumName = metaDict[VLCMetaInformationAlbum];
  684. trackNumber = metaDict[VLCMetaInformationTrackNumber];
  685. }
  686. }
  687. if (!mediaIsAudioOnly) {
  688. /* either what we are playing is not a file known to MLKit or
  689. * MLKit fails to acknowledge that it is audio-only.
  690. * Either way, do a more expensive check to see if it is really audio-only */
  691. NSArray *tracks = _mediaPlayer.media.tracksInformation;
  692. NSUInteger trackCount = tracks.count;
  693. mediaIsAudioOnly = YES;
  694. for (NSUInteger x = 0 ; x < trackCount; x++) {
  695. if ([[tracks[x] objectForKey:VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  696. mediaIsAudioOnly = NO;
  697. break;
  698. }
  699. }
  700. }
  701. if (mediaIsAudioOnly) {
  702. artworkImage = [VLCThumbnailsCache thumbnailForManagedObject:item];
  703. if (artworkImage) {
  704. if (artist)
  705. title = [title stringByAppendingFormat:@" — %@", artist];
  706. if (albumName)
  707. title = [title stringByAppendingFormat:@" — %@", albumName];
  708. }
  709. if (title.length < 1)
  710. title = [[_mediaPlayer.media url] lastPathComponent];
  711. }
  712. /* populate delegate with metadata info */
  713. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:title:artwork:artist:album:audioOnly:)])
  714. [self.delegate displayMetadataForPlaybackController:self
  715. title:title
  716. artwork:artworkImage
  717. artist:artist
  718. album:albumName
  719. audioOnly:mediaIsAudioOnly];
  720. /* populate now playing info center with metadata information */
  721. NSMutableDictionary *currentlyPlayingTrackInfo = [NSMutableDictionary dictionary];
  722. currentlyPlayingTrackInfo[MPMediaItemPropertyPlaybackDuration] = @(_mediaPlayer.media.length.intValue / 1000.);
  723. currentlyPlayingTrackInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = @(_mediaPlayer.time.intValue / 1000.);
  724. currentlyPlayingTrackInfo[MPNowPlayingInfoPropertyPlaybackRate] = @(_mediaPlayer.isPlaying ? _mediaPlayer.rate : 0.0);
  725. /* don't leak sensitive information to the OS, if passcode lock is enabled */
  726. if (![[VLCKeychainCoordinator defaultCoordinator] passcodeLockEnabled]) {
  727. if (title)
  728. currentlyPlayingTrackInfo[MPMediaItemPropertyTitle] = title;
  729. if (artist.length > 0)
  730. currentlyPlayingTrackInfo[MPMediaItemPropertyArtist] = artist;
  731. if (albumName.length > 0)
  732. currentlyPlayingTrackInfo[MPMediaItemPropertyAlbumTitle] = albumName;
  733. if ([trackNumber intValue] > 0)
  734. currentlyPlayingTrackInfo[MPMediaItemPropertyAlbumTrackNumber] = trackNumber;
  735. /* FIXME: UGLY HACK
  736. * iOS 8.2 and 8.3 include an issue which will lead to a termination of the client app if we set artwork
  737. * when the playback initialized through the watch extension
  738. * radar://pending */
  739. if ([WKInterfaceDevice class] != nil) {
  740. if ([WKInterfaceDevice currentDevice] != nil)
  741. goto setstuff;
  742. }
  743. if (artworkImage) {
  744. MPMediaItemArtwork *mpartwork = [[MPMediaItemArtwork alloc] initWithImage:artworkImage];
  745. currentlyPlayingTrackInfo[MPMediaItemPropertyArtwork] = mpartwork;
  746. }
  747. }
  748. setstuff:
  749. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = currentlyPlayingTrackInfo;
  750. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  751. _title = title;
  752. _artist = artist;
  753. _albumName = albumName;
  754. _artworkImage = artworkImage;
  755. _mediaIsAudioOnly = mediaIsAudioOnly;
  756. }
  757. - (void)_recoverLastPlaybackStateOfItem:(MLFile *)item
  758. {
  759. if (item) {
  760. if (_mediaPlayer.numberOfAudioTracks > 2) {
  761. if (item.lastAudioTrack.intValue > 0)
  762. _mediaPlayer.currentAudioTrackIndex = item.lastAudioTrack.intValue;
  763. }
  764. if (_mediaPlayer.numberOfSubtitlesTracks > 2) {
  765. if (item.lastSubtitleTrack.intValue > 0)
  766. _mediaPlayer.currentVideoSubTitleIndex = item.lastSubtitleTrack.intValue;
  767. }
  768. CGFloat lastPosition = .0;
  769. NSInteger duration = 0;
  770. if (item.lastPosition)
  771. lastPosition = item.lastPosition.floatValue;
  772. duration = item.duration.intValue;
  773. if (lastPosition < .95 && _mediaPlayer.position < lastPosition && (duration * lastPosition - duration) < -60000)
  774. _mediaPlayer.position = lastPosition;
  775. }
  776. }
  777. - (void)recoverDisplayedMetadata
  778. {
  779. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:title:artwork:artist:album:audioOnly:)])
  780. [self.delegate displayMetadataForPlaybackController:self
  781. title:_title
  782. artwork:_artworkImage
  783. artist:_artist
  784. album:_albumName
  785. audioOnly:_mediaIsAudioOnly];
  786. }
  787. - (void)recoverPlaybackState
  788. {
  789. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  790. [self.delegate mediaPlayerStateChanged:_mediaPlayer.state
  791. isPlaying:self.isPlaying
  792. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  793. currentMediaHasChapters:self.currentMediaHasChapters
  794. forPlaybackController:self];
  795. }
  796. - (void)scheduleSleepTimerWithInterval:(NSTimeInterval)timeInterval
  797. {
  798. if (_sleepTimer) {
  799. [_sleepTimer invalidate];
  800. _sleepTimer = nil;
  801. }
  802. _sleepTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(stopPlayback) userInfo:nil repeats:NO];
  803. }
  804. #pragma mark - remote events
  805. static inline NSArray * RemoteCommandCenterCommandsToHandle(MPRemoteCommandCenter *cc)
  806. {
  807. /* commmented out other available commands which we don't support now but may
  808. * support at some point in the future */
  809. return @[cc.pauseCommand, cc.playCommand, cc.stopCommand, cc.togglePlayPauseCommand,
  810. cc.nextTrackCommand, cc.previousTrackCommand,
  811. cc.skipForwardCommand, cc.skipBackwardCommand,
  812. // cc.seekForwardCommand, cc.seekBackwardCommand,
  813. // cc.ratingCommand,
  814. cc.changePlaybackRateCommand,
  815. // cc.likeCommand,cc.dislikeCommand,cc.bookmarkCommand,
  816. ];
  817. }
  818. - (void)subscribeRemoteCommands
  819. {
  820. /* pre iOS 7.1 */
  821. if (![MPRemoteCommandCenter class]) {
  822. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  823. return;
  824. }
  825. /* for iOS 7.1 and above: */
  826. MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
  827. /*
  828. * since the control center and lockscreen shows only either skipForward/Backward
  829. * or next/previousTrack buttons but prefers skip buttons,
  830. * we only enable skip buttons if we have a no medialist
  831. */
  832. BOOL enableSkip = [VLCPlaybackController sharedInstance].mediaList == nil;
  833. commandCenter.skipForwardCommand.enabled = enableSkip;
  834. commandCenter.skipBackwardCommand.enabled = enableSkip;
  835. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  836. NSNumber *forwardSkip = [defaults valueForKey:kVLCSettingPlaybackForwardSkipLength];
  837. commandCenter.skipForwardCommand.preferredIntervals = @[forwardSkip];
  838. NSNumber *backwardSkip = [defaults valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  839. commandCenter.skipBackwardCommand.preferredIntervals = @[backwardSkip];
  840. NSArray *supportedPlaybackRates = @[@(0.5),@(0.75),@(1.0),@(1.25),@(1.5),@(1.75),@(2.0)];
  841. commandCenter.changePlaybackRateCommand.supportedPlaybackRates = supportedPlaybackRates;
  842. NSArray *commandsToSubscribe = RemoteCommandCenterCommandsToHandle(commandCenter);
  843. for (MPRemoteCommand *command in commandsToSubscribe) {
  844. [command addTarget:self action:@selector(remoteCommandEvent:)];
  845. }
  846. }
  847. - (void)unsubscribeFromRemoteCommand
  848. {
  849. /* pre iOS 7.1 */
  850. if (![MPRemoteCommandCenter class]) {
  851. [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
  852. return;
  853. }
  854. /* for iOS 7.1 and above: */
  855. MPRemoteCommandCenter *cc = [MPRemoteCommandCenter sharedCommandCenter];
  856. NSArray *commmandsToRemoveFrom = RemoteCommandCenterCommandsToHandle(cc);
  857. for (MPRemoteCommand *command in commmandsToRemoveFrom) {
  858. [command removeTarget:self];
  859. }
  860. }
  861. - (MPRemoteCommandHandlerStatus )remoteCommandEvent:(MPRemoteCommandEvent *)event
  862. {
  863. MPRemoteCommandCenter *cc = [MPRemoteCommandCenter sharedCommandCenter];
  864. MPRemoteCommandHandlerStatus result = MPRemoteCommandHandlerStatusSuccess;
  865. if (event.command == cc.pauseCommand) {
  866. [_listPlayer pause];
  867. } else if (event.command == cc.playCommand) {
  868. [_listPlayer play];
  869. } else if (event.command == cc.stopCommand) {
  870. [_listPlayer stop];
  871. } else if (event.command == cc.togglePlayPauseCommand) {
  872. [self playPause];
  873. } else if (event.command == cc.nextTrackCommand) {
  874. result = [_listPlayer next] ? MPRemoteCommandHandlerStatusSuccess : MPRemoteCommandHandlerStatusNoSuchContent;
  875. } else if (event.command == cc.previousTrackCommand) {
  876. result = [_listPlayer previous] ? MPRemoteCommandHandlerStatusSuccess : MPRemoteCommandHandlerStatusNoSuchContent;
  877. } else if (event.command == cc.skipForwardCommand) {
  878. if ([event isKindOfClass:[MPSkipIntervalCommandEvent class]]) {
  879. MPSkipIntervalCommandEvent *skipEvent = (MPSkipIntervalCommandEvent *)event;
  880. [_mediaPlayer jumpForward:skipEvent.interval];
  881. } else {
  882. result = MPRemoteCommandHandlerStatusCommandFailed;
  883. }
  884. } else if (event.command == cc.skipBackwardCommand) {
  885. if ([event isKindOfClass:[MPSkipIntervalCommandEvent class]]) {
  886. MPSkipIntervalCommandEvent *skipEvent = (MPSkipIntervalCommandEvent *)event;
  887. [_mediaPlayer jumpBackward:skipEvent.interval];
  888. } else {
  889. result = MPRemoteCommandHandlerStatusCommandFailed;
  890. }
  891. } else if (event.command == cc.changePlaybackRateCommand) {
  892. if ([event isKindOfClass:[MPChangePlaybackRateCommandEvent class]]) {
  893. MPChangePlaybackRateCommandEvent *rateEvent = (MPChangePlaybackRateCommandEvent *)event;
  894. [_mediaPlayer setRate:rateEvent.playbackRate];
  895. } else {
  896. result = MPRemoteCommandHandlerStatusCommandFailed;
  897. }
  898. /* stubs for when we want to support the other available commands */
  899. // } else if (event.command == cc.seekForwardCommand) {
  900. // } else if (event.command == cc.seekBackwardCommand) {
  901. // } else if (event.command == cc.ratingCommand) {
  902. // } else if (event.command == cc.likeCommand) {
  903. // } else if (event.command == cc.dislikeCommand) {
  904. // } else if (event.command == cc.bookmarkCommand) {
  905. } else {
  906. APLog(@"%s Unsupported remote control event: %@",__PRETTY_FUNCTION__,event);
  907. result = MPRemoteCommandHandlerStatusCommandFailed;
  908. }
  909. if (result == MPRemoteCommandHandlerStatusCommandFailed)
  910. APLog(@"%s Wasn't able to handle remote control event: %@",__PRETTY_FUNCTION__,event);
  911. return result;
  912. }
  913. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  914. {
  915. switch (event.subtype) {
  916. case UIEventSubtypeRemoteControlPlay:
  917. [_listPlayer play];
  918. break;
  919. case UIEventSubtypeRemoteControlPause:
  920. [_listPlayer pause];
  921. break;
  922. case UIEventSubtypeRemoteControlTogglePlayPause:
  923. [self playPause];
  924. break;
  925. case UIEventSubtypeRemoteControlNextTrack:
  926. [self forward];
  927. break;
  928. case UIEventSubtypeRemoteControlPreviousTrack:
  929. [self backward];
  930. break;
  931. case UIEventSubtypeRemoteControlStop:
  932. [self stopPlayback];
  933. break;
  934. default:
  935. break;
  936. }
  937. }
  938. #pragma mark - background interaction
  939. - (void)applicationWillResignActive:(NSNotification *)aNotification
  940. {
  941. [self _savePlaybackState];
  942. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  943. if ([_mediaPlayer isPlaying]) {
  944. [_mediaPlayer pause];
  945. _shouldResumePlaying = YES;
  946. }
  947. }
  948. }
  949. - (void)applicationDidEnterBackground:(NSNotification *)notification
  950. {
  951. _preBackgroundWrapperView = _videoOutputViewWrapper;
  952. [self setVideoOutputView:nil];
  953. if (_mediaPlayer.audioTrackIndexes.count > 0)
  954. _mediaPlayer.currentVideoTrackIndex = -1;
  955. }
  956. - (void)applicationDidBecomeActive:(NSNotification *)notification
  957. {
  958. if (_preBackgroundWrapperView) {
  959. [self setVideoOutputView:_preBackgroundWrapperView];
  960. _preBackgroundWrapperView = nil;
  961. }
  962. if (_mediaPlayer.numberOfVideoTracks > 0) {
  963. /* re-enable video decoding */
  964. _mediaPlayer.currentVideoTrackIndex = 1;
  965. }
  966. if (_shouldResumePlaying) {
  967. _shouldResumePlaying = NO;
  968. [_listPlayer play];
  969. }
  970. }
  971. #pragma mark - helpers
  972. - (NSString *)_resolveFontName
  973. {
  974. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  975. BOOL bold = [[defaults objectForKey:kVLCSettingSubtitlesBoldFont] boolValue];
  976. NSString *font = [defaults objectForKey:kVLCSettingSubtitlesFont];
  977. NSDictionary *fontMap = @{
  978. @"AmericanTypewriter": @"AmericanTypewriter-Bold",
  979. @"ArialMT": @"Arial-BoldMT",
  980. @"ArialHebrew": @"ArialHebrew-Bold",
  981. @"ChalkboardSE-Regular": @"ChalkboardSE-Bold",
  982. @"CourierNewPSMT": @"CourierNewPS-BoldMT",
  983. @"Georgia": @"Georgia-Bold",
  984. @"GillSans": @"GillSans-Bold",
  985. @"GujaratiSangamMN": @"GujaratiSangamMN-Bold",
  986. @"STHeitiSC-Light": @"STHeitiSC-Medium",
  987. @"STHeitiTC-Light": @"STHeitiTC-Medium",
  988. @"HelveticaNeue": @"HelveticaNeue-Bold",
  989. @"HiraKakuProN-W3": @"HiraKakuProN-W6",
  990. @"HiraMinProN-W3": @"HiraMinProN-W6",
  991. @"HoeflerText-Regular": @"HoeflerText-Black",
  992. @"Kailasa": @"Kailasa-Bold",
  993. @"KannadaSangamMN": @"KannadaSangamMN-Bold",
  994. @"MalayalamSangamMN": @"MalayalamSangamMN-Bold",
  995. @"OriyaSangamMN": @"OriyaSangamMN-Bold",
  996. @"SinhalaSangamMN": @"SinhalaSangamMN-Bold",
  997. @"SnellRoundhand": @"SnellRoundhand-Bold",
  998. @"TamilSangamMN": @"TamilSangamMN-Bold",
  999. @"TeluguSangamMN": @"TeluguSangamMN-Bold",
  1000. @"TimesNewRomanPSMT": @"TimesNewRomanPS-BoldMT",
  1001. @"Zapfino": @"Zapfino"
  1002. };
  1003. if (!bold) {
  1004. return font;
  1005. } else {
  1006. return fontMap[font];
  1007. }
  1008. }
  1009. @end