VLCPlaybackController.m 45 KB

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