VLCPlaybackController.m 46 KB

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