VLCPlaybackController.m 44 KB

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