VLCPlaybackController.m 45 KB

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