VLCPlaybackController.m 45 KB

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