VLCPlaybackController.m 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  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. [_mediaPlayer addObserver:self forKeyPath:@"time" options:0 context:nil];
  234. [_mediaPlayer addObserver:self forKeyPath:@"remainingTime" options:0 context:nil];
  235. if (self.mediaList)
  236. [_listPlayer playItemAtIndex:self.itemInMediaListToBePlayedFirst];
  237. else
  238. [_listPlayer playMedia:_listPlayer.rootMedia];
  239. if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  240. [self.delegate prepareForMediaPlayback:self];
  241. _currentAspectRatioMask = 0;
  242. _mediaPlayer.videoAspectRatio = NULL;
  243. [self subscribeRemoteCommands];
  244. _playerIsSetup = YES;
  245. _mediaWasJustStarted = 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 ([self.delegate respondsToSelector:@selector(playbackPositionUpdated:)])
  365. [self.delegate playbackPositionUpdated:self];
  366. }
  367. - (NSInteger)mediaDuration
  368. {
  369. return _listPlayer.mediaPlayer.media.length.intValue;;
  370. }
  371. - (BOOL)isPlaying
  372. {
  373. return _mediaPlayer.isPlaying;
  374. }
  375. - (VLCRepeatMode)repeatMode
  376. {
  377. return _listPlayer.repeatMode;
  378. }
  379. - (void)setRepeatMode:(VLCRepeatMode)repeatMode
  380. {
  381. _listPlayer.repeatMode = repeatMode;
  382. }
  383. - (BOOL)currentMediaHasChapters
  384. {
  385. return [_mediaPlayer countOfTitles] > 1 || [_mediaPlayer chaptersForTitleIndex:_mediaPlayer.currentTitleIndex].count > 1;
  386. }
  387. - (BOOL)currentMediaHasTrackToChooseFrom
  388. {
  389. return [[_mediaPlayer audioTrackIndexes] count] > 2 || [[_mediaPlayer videoSubTitlesIndexes] count] > 1;
  390. }
  391. - (BOOL)activePlaybackSession
  392. {
  393. return _activeSession;
  394. }
  395. - (BOOL)audioOnlyPlaybackSession
  396. {
  397. return _mediaIsAudioOnly;
  398. }
  399. - (float)playbackRate
  400. {
  401. float f_rate = _mediaPlayer.rate;
  402. _currentPlaybackRate = f_rate;
  403. return f_rate;
  404. }
  405. - (void)setPlaybackRate:(float)playbackRate
  406. {
  407. if (_currentPlaybackRate != playbackRate)
  408. [_mediaPlayer setRate:playbackRate];
  409. _currentPlaybackRate = playbackRate;
  410. }
  411. - (void)setAudioDelay:(float)audioDelay
  412. {
  413. _mediaPlayer.currentAudioPlaybackDelay = 1000000.*audioDelay;
  414. }
  415. - (float)audioDelay
  416. {
  417. return _mediaPlayer.currentAudioPlaybackDelay/1000000.;
  418. }
  419. -(void)setSubtitleDelay:(float)subtitleDeleay
  420. {
  421. _mediaPlayer.currentVideoSubTitleDelay = 1000000.*subtitleDeleay;
  422. }
  423. - (float)subtitleDelay
  424. {
  425. return _mediaPlayer.currentVideoSubTitleDelay/1000000.;
  426. }
  427. - (void)mediaPlayerStateChanged:(NSNotification *)aNotification
  428. {
  429. VLCMediaPlayerState currentState = _mediaPlayer.state;
  430. if (currentState == VLCMediaPlayerStateBuffering) {
  431. /* attach delegate */
  432. _mediaPlayer.media.delegate = self;
  433. /* on-the-fly values through hidden API */
  434. [_mediaPlayer performSelector:@selector(setTextRendererFont:) withObject:[self _resolveFontName]];
  435. [_mediaPlayer performSelector:@selector(setTextRendererFontSize:) withObject:[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingSubtitlesFontSize]];
  436. [_mediaPlayer performSelector:@selector(setTextRendererFontColor:) withObject:[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingSubtitlesFontColor]];
  437. } else if (currentState == VLCMediaPlayerStateError) {
  438. _playbackFailed = YES;
  439. [self stopPlayback];
  440. } else if ((currentState == VLCMediaPlayerStateEnded || currentState == VLCMediaPlayerStateStopped) && _listPlayer.repeatMode == VLCDoNotRepeat) {
  441. if ([_listPlayer.mediaList indexOfMedia:_mediaPlayer.media] == _listPlayer.mediaList.count - 1) {
  442. [self stopPlayback];
  443. return;
  444. }
  445. }
  446. /* disable video decoding if we have no place to show */
  447. if (_mediaPlayer.numberOfAudioTracks > 0) {
  448. if (_videoOutputViewWrapper == nil)
  449. _mediaPlayer.currentVideoTrackIndex = -1;
  450. }
  451. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  452. [self.delegate mediaPlayerStateChanged:currentState
  453. isPlaying:_mediaPlayer.isPlaying
  454. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  455. currentMediaHasChapters:self.currentMediaHasChapters
  456. forPlaybackController:self];
  457. [self setNeedsMetadataUpdate];
  458. }
  459. #pragma mark - playback controls
  460. - (void)playPause
  461. {
  462. if ([_mediaPlayer isPlaying]) {
  463. [_listPlayer pause];
  464. [self _savePlaybackState];
  465. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
  466. } else {
  467. [_listPlayer play];
  468. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidResume object:self];
  469. }
  470. }
  471. - (void)forward
  472. {
  473. if (_mediaList) {
  474. [_listPlayer next];
  475. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  476. } else {
  477. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackForwardSkipLength];
  478. [_mediaPlayer jumpForward:skipLength.intValue];
  479. }
  480. }
  481. - (void)backward
  482. {
  483. if (_mediaList) {
  484. [_listPlayer previous];
  485. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  486. }
  487. else {
  488. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  489. [_mediaPlayer jumpBackward:skipLength.intValue];
  490. }
  491. }
  492. - (void)switchAspectRatio
  493. {
  494. NSUInteger count = [_aspectRatios count];
  495. if (_currentAspectRatioMask + 1 > count - 1) {
  496. _mediaPlayer.videoAspectRatio = NULL;
  497. _mediaPlayer.videoCropGeometry = NULL;
  498. _currentAspectRatioMask = 0;
  499. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  500. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), NSLocalizedString(@"DEFAULT", nil)] forPlaybackController:self];
  501. } else {
  502. _currentAspectRatioMask++;
  503. if ([_aspectRatios[_currentAspectRatioMask] isEqualToString:@"FILL_TO_SCREEN"]) {
  504. UIScreen *screen;
  505. if (![[UIDevice currentDevice] hasExternalDisplay])
  506. screen = [UIScreen mainScreen];
  507. else
  508. screen = [UIScreen screens][1];
  509. float f_ar = screen.bounds.size.width / screen.bounds.size.height;
  510. if (f_ar == (float)(640./1136.)) // iPhone 5 aka 16:9.01
  511. _mediaPlayer.videoCropGeometry = "16:9";
  512. else if (f_ar == (float)(2./3.)) // all other iPhones
  513. _mediaPlayer.videoCropGeometry = "16:10"; // libvlc doesn't support 2:3 crop
  514. else if (f_ar == (float)(1. + (1./3.))) // all iPads
  515. _mediaPlayer.videoCropGeometry = "4:3";
  516. else if (f_ar == .5625) // AirPlay
  517. _mediaPlayer.videoCropGeometry = "16:9";
  518. else
  519. APLog(@"unknown screen format %f, can't crop", f_ar);
  520. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  521. [self.delegate showStatusMessage:NSLocalizedString(@"FILL_TO_SCREEN", nil) forPlaybackController:self];
  522. return;
  523. }
  524. _mediaPlayer.videoCropGeometry = NULL;
  525. _mediaPlayer.videoAspectRatio = (char *)[_aspectRatios[_currentAspectRatioMask] UTF8String];
  526. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  527. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), _aspectRatios[_currentAspectRatioMask]] forPlaybackController:self];
  528. }
  529. }
  530. - (void)setVideoOutputView:(UIView *)videoOutputView
  531. {
  532. if (videoOutputView) {
  533. if ([_actualVideoOutputView superview] != nil)
  534. [_actualVideoOutputView removeFromSuperview];
  535. _actualVideoOutputView.frame = (CGRect){CGPointZero, videoOutputView.frame.size};
  536. [_actualVideoOutputView layoutSubviews];
  537. [_actualVideoOutputView updateConstraints];
  538. if (_mediaPlayer.currentVideoTrackIndex == -1)
  539. _mediaPlayer.currentVideoTrackIndex = 0;
  540. [videoOutputView addSubview:_actualVideoOutputView];
  541. } else
  542. [_actualVideoOutputView removeFromSuperview];
  543. _videoOutputViewWrapper = videoOutputView;
  544. }
  545. - (UIView *)videoOutputView
  546. {
  547. return _videoOutputViewWrapper;
  548. }
  549. #pragma mark - equalizer
  550. - (void)setAmplification:(CGFloat)amplification forBand:(unsigned int)index
  551. {
  552. if (!_mediaPlayer.equalizerEnabled)
  553. [_mediaPlayer setEqualizerEnabled:YES];
  554. [_mediaPlayer setAmplification:amplification forBand:index];
  555. // For some reason we have to apply again preamp to apply change
  556. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  557. }
  558. - (CGFloat)amplificationOfBand:(unsigned int)index
  559. {
  560. return [_mediaPlayer amplificationOfBand:index];
  561. }
  562. - (NSArray *)equalizerProfiles
  563. {
  564. return _mediaPlayer.equalizerProfiles;
  565. }
  566. - (void)resetEqualizerFromProfile:(unsigned int)profile
  567. {
  568. [[NSUserDefaults standardUserDefaults] setObject:@(profile) forKey:kVLCSettingEqualizerProfile];
  569. [_mediaPlayer resetEqualizerFromProfile:profile];
  570. }
  571. - (void)setPreAmplification:(CGFloat)preAmplification
  572. {
  573. if (!_mediaPlayer.equalizerEnabled)
  574. [_mediaPlayer setEqualizerEnabled:YES];
  575. [_mediaPlayer setPreAmplification:preAmplification];
  576. }
  577. - (CGFloat)preAmplification
  578. {
  579. return [_mediaPlayer preAmplification];
  580. }
  581. #pragma mark - AVSession delegate
  582. - (void)beginInterruption
  583. {
  584. if ([_mediaPlayer isPlaying]) {
  585. [_mediaPlayer pause];
  586. _shouldResumePlaying = YES;
  587. }
  588. }
  589. - (void)endInterruption
  590. {
  591. if (_shouldResumePlaying) {
  592. [_mediaPlayer play];
  593. _shouldResumePlaying = NO;
  594. }
  595. }
  596. - (void)audioSessionRouteChange:(NSNotification *)notification
  597. {
  598. NSArray *outputs = [[AVAudioSession sharedInstance] currentRoute].outputs;
  599. NSString *portName = [[outputs objectAtIndex:0] portName];
  600. if (![portName isEqualToString:@"Headphones"] && [_mediaPlayer isPlaying])
  601. [_listPlayer pause];
  602. }
  603. #pragma mark - Managing the media item
  604. - (void)setUrl:(NSURL *)url
  605. {
  606. [self stopPlayback];
  607. _url = url;
  608. _playerIsSetup = NO;
  609. }
  610. - (void)setMediaList:(VLCMediaList *)mediaList
  611. {
  612. [self stopPlayback];
  613. _mediaList = mediaList;
  614. _playerIsSetup = NO;
  615. }
  616. - (MLFile *)currentlyPlayingMediaFile {
  617. if (self.mediaList) {
  618. NSArray *results = [MLFile fileForURL:_mediaPlayer.media.url];
  619. return results.firstObject;
  620. }
  621. return nil;
  622. }
  623. #pragma mark - metadata handling
  624. - (void)mediaDidFinishParsing:(VLCMedia *)aMedia
  625. {
  626. [self setNeedsMetadataUpdate];
  627. }
  628. - (void)mediaMetaDataDidChange:(VLCMedia*)aMedia
  629. {
  630. [self setNeedsMetadataUpdate];
  631. }
  632. - (void)setNeedsMetadataUpdate
  633. {
  634. if (_needsMetadataUpdate == NO) {
  635. _needsMetadataUpdate = YES;
  636. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  637. [self _updateDisplayedMetadata];
  638. });
  639. }
  640. }
  641. - (void)_updateDisplayedMetadata
  642. {
  643. _needsMetadataUpdate = NO;
  644. MLFile *item;
  645. NSNumber *trackNumber;
  646. NSString *title;
  647. NSString *artist;
  648. NSString *albumName;
  649. UIImage* artworkImage;
  650. BOOL mediaIsAudioOnly = NO;
  651. if (self.mediaList) {
  652. NSArray *matches = [MLFile fileForURL:_mediaPlayer.media.url];
  653. item = matches.firstObject;
  654. }
  655. if (item) {
  656. if (item.isAlbumTrack) {
  657. title = item.albumTrack.title;
  658. artist = item.albumTrack.artist;
  659. albumName = item.albumTrack.album.name;
  660. } else
  661. title = item.title;
  662. /* MLKit knows better than us if this thing is audio only or not */
  663. mediaIsAudioOnly = [item isSupportedAudioFile];
  664. } else {
  665. NSDictionary * metaDict = _mediaPlayer.media.metaDictionary;
  666. if (metaDict) {
  667. title = metaDict[VLCMetaInformationNowPlaying] ? metaDict[VLCMetaInformationNowPlaying] : metaDict[VLCMetaInformationTitle];
  668. artist = metaDict[VLCMetaInformationArtist];
  669. albumName = metaDict[VLCMetaInformationAlbum];
  670. trackNumber = metaDict[VLCMetaInformationTrackNumber];
  671. }
  672. }
  673. if (!mediaIsAudioOnly) {
  674. /* either what we are playing is not a file known to MLKit or
  675. * MLKit fails to acknowledge that it is audio-only.
  676. * Either way, do a more expensive check to see if it is really audio-only */
  677. NSArray *tracks = _mediaPlayer.media.tracksInformation;
  678. NSUInteger trackCount = tracks.count;
  679. mediaIsAudioOnly = YES;
  680. for (NSUInteger x = 0 ; x < trackCount; x++) {
  681. if ([[tracks[x] objectForKey:VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  682. mediaIsAudioOnly = NO;
  683. break;
  684. }
  685. }
  686. }
  687. if (mediaIsAudioOnly) {
  688. artworkImage = [VLCThumbnailsCache thumbnailForManagedObject:item];
  689. if (artworkImage) {
  690. if (artist)
  691. title = [title stringByAppendingFormat:@" — %@", artist];
  692. if (albumName)
  693. title = [title stringByAppendingFormat:@" — %@", albumName];
  694. }
  695. if (title.length < 1)
  696. title = [[_mediaPlayer.media url] lastPathComponent];
  697. } else if (_mediaWasJustStarted) {
  698. _mediaWasJustStarted = NO;
  699. if (item) {
  700. if (_mediaPlayer.numberOfAudioTracks > 2) {
  701. if (item.lastAudioTrack.intValue > 0)
  702. _mediaPlayer.currentAudioTrackIndex = item.lastAudioTrack.intValue;
  703. }
  704. if (_mediaPlayer.numberOfSubtitlesTracks > 2) {
  705. if (item.lastSubtitleTrack.intValue > 0)
  706. _mediaPlayer.currentVideoSubTitleIndex = item.lastSubtitleTrack.intValue;
  707. }
  708. CGFloat lastPosition = .0;
  709. NSInteger duration = 0;
  710. if (item.lastPosition)
  711. lastPosition = item.lastPosition.floatValue;
  712. duration = item.duration.intValue;
  713. if (lastPosition < .95 && _mediaPlayer.position < lastPosition && (duration * lastPosition - duration) < -60000)
  714. _mediaPlayer.position = lastPosition;
  715. }
  716. }
  717. /* populate delegate with metadata info */
  718. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:title:artwork:artist:album:audioOnly:)])
  719. [self.delegate displayMetadataForPlaybackController:self
  720. title:title
  721. artwork:artworkImage
  722. artist:artist
  723. album:albumName
  724. audioOnly:mediaIsAudioOnly];
  725. /* populate now playing info center with metadata information */
  726. NSMutableDictionary *currentlyPlayingTrackInfo = [NSMutableDictionary dictionary];
  727. currentlyPlayingTrackInfo[MPMediaItemPropertyPlaybackDuration] = @(_mediaPlayer.media.length.intValue / 1000.);
  728. currentlyPlayingTrackInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = @(_mediaPlayer.time.intValue / 1000.);
  729. currentlyPlayingTrackInfo[MPNowPlayingInfoPropertyPlaybackRate] = @(_mediaPlayer.isPlaying ? _mediaPlayer.rate : 0.0);
  730. /* don't leak sensitive information to the OS, if passcode lock is enabled */
  731. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingPasscodeOnKey] boolValue]) {
  732. if (title)
  733. currentlyPlayingTrackInfo[MPMediaItemPropertyTitle] = title;
  734. if (artist.length > 0)
  735. currentlyPlayingTrackInfo[MPMediaItemPropertyArtist] = artist;
  736. if (albumName.length > 0)
  737. currentlyPlayingTrackInfo[MPMediaItemPropertyAlbumTitle] = albumName;
  738. if ([trackNumber intValue] > 0)
  739. currentlyPlayingTrackInfo[MPMediaItemPropertyAlbumTrackNumber] = trackNumber;
  740. /* FIXME: UGLY HACK
  741. * iOS 8.2 and 8.3 include an issue which will lead to a termination of the client app if we set artwork
  742. * when the playback initialized through the watch extension
  743. * radar://pending */
  744. if ([WKInterfaceDevice class] != nil) {
  745. if ([WKInterfaceDevice currentDevice] != nil)
  746. goto setstuff;
  747. }
  748. if (artworkImage) {
  749. MPMediaItemArtwork *mpartwork = [[MPMediaItemArtwork alloc] initWithImage:artworkImage];
  750. currentlyPlayingTrackInfo[MPMediaItemPropertyArtwork] = mpartwork;
  751. }
  752. }
  753. setstuff:
  754. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = currentlyPlayingTrackInfo;
  755. [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
  756. _title = title;
  757. _artist = artist;
  758. _albumName = albumName;
  759. _artworkImage = artworkImage;
  760. _mediaIsAudioOnly = mediaIsAudioOnly;
  761. }
  762. - (void)recoverDisplayedMetadata
  763. {
  764. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:title:artwork:artist:album:audioOnly:)])
  765. [self.delegate displayMetadataForPlaybackController:self
  766. title:_title
  767. artwork:_artworkImage
  768. artist:_artist
  769. album:_albumName
  770. audioOnly:_mediaIsAudioOnly];
  771. }
  772. - (void)recoverPlaybackState
  773. {
  774. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  775. [self.delegate mediaPlayerStateChanged:_mediaPlayer.state
  776. isPlaying:self.isPlaying
  777. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  778. currentMediaHasChapters:self.currentMediaHasChapters
  779. forPlaybackController:self];
  780. }
  781. - (void)scheduleSleepTimerWithInterval:(NSTimeInterval)timeInterval
  782. {
  783. if (_sleepTimer) {
  784. [_sleepTimer invalidate];
  785. _sleepTimer = nil;
  786. }
  787. _sleepTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(stopPlayback) userInfo:nil repeats:NO];
  788. }
  789. #pragma mark - remote events
  790. static inline NSArray * RemoteCommandCenterCommandsToHandle(MPRemoteCommandCenter *cc)
  791. {
  792. /* commmented out other available commands which we don't support now but may
  793. * support at some point in the future */
  794. return @[cc.pauseCommand, cc.playCommand, cc.stopCommand, cc.togglePlayPauseCommand,
  795. cc.nextTrackCommand, cc.previousTrackCommand,
  796. cc.skipForwardCommand, cc.skipBackwardCommand,
  797. // cc.seekForwardCommand, cc.seekBackwardCommand,
  798. // cc.ratingCommand,
  799. cc.changePlaybackRateCommand,
  800. // cc.likeCommand,cc.dislikeCommand,cc.bookmarkCommand,
  801. ];
  802. }
  803. - (void)subscribeRemoteCommands
  804. {
  805. /* pre iOS 7.1 */
  806. if (![MPRemoteCommandCenter class]) {
  807. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  808. return;
  809. }
  810. /* for iOS 7.1 and above: */
  811. MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
  812. /*
  813. * since the control center and lockscreen shows only either skipForward/Backward
  814. * or next/previousTrack buttons but prefers skip buttons,
  815. * we only enable skip buttons if we have a no medialist
  816. */
  817. BOOL enableSkip = [VLCPlaybackController sharedInstance].mediaList == nil;
  818. commandCenter.skipForwardCommand.enabled = enableSkip;
  819. commandCenter.skipBackwardCommand.enabled = enableSkip;
  820. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  821. NSNumber *forwardSkip = [defaults valueForKey:kVLCSettingPlaybackForwardSkipLength];
  822. commandCenter.skipForwardCommand.preferredIntervals = @[forwardSkip];
  823. NSNumber *backwardSkip = [defaults valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  824. commandCenter.skipBackwardCommand.preferredIntervals = @[backwardSkip];
  825. NSArray *supportedPlaybackRates = @[@(0.5),@(0.75),@(1.0),@(1.25),@(1.5),@(1.75),@(2.0)];
  826. commandCenter.changePlaybackRateCommand.supportedPlaybackRates = supportedPlaybackRates;
  827. NSArray *commandsToSubscribe = RemoteCommandCenterCommandsToHandle(commandCenter);
  828. for (MPRemoteCommand *command in commandsToSubscribe) {
  829. [command addTarget:self action:@selector(remoteCommandEvent:)];
  830. }
  831. }
  832. - (void)unsubscribeFromRemoteCommand
  833. {
  834. /* pre iOS 7.1 */
  835. if (![MPRemoteCommandCenter class]) {
  836. [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
  837. return;
  838. }
  839. /* for iOS 7.1 and above: */
  840. MPRemoteCommandCenter *cc = [MPRemoteCommandCenter sharedCommandCenter];
  841. NSArray *commmandsToRemoveFrom = RemoteCommandCenterCommandsToHandle(cc);
  842. for (MPRemoteCommand *command in commmandsToRemoveFrom) {
  843. [command removeTarget:self];
  844. }
  845. }
  846. - (MPRemoteCommandHandlerStatus )remoteCommandEvent:(MPRemoteCommandEvent *)event
  847. {
  848. MPRemoteCommandCenter *cc = [MPRemoteCommandCenter sharedCommandCenter];
  849. MPRemoteCommandHandlerStatus result = MPRemoteCommandHandlerStatusSuccess;
  850. if (event.command == cc.pauseCommand) {
  851. [_listPlayer pause];
  852. } else if (event.command == cc.playCommand) {
  853. [_listPlayer play];
  854. } else if (event.command == cc.stopCommand) {
  855. [_listPlayer stop];
  856. } else if (event.command == cc.togglePlayPauseCommand) {
  857. [self playPause];
  858. } else if (event.command == cc.nextTrackCommand) {
  859. result = [_listPlayer next] ? MPRemoteCommandHandlerStatusSuccess : MPRemoteCommandHandlerStatusNoSuchContent;
  860. } else if (event.command == cc.previousTrackCommand) {
  861. result = [_listPlayer previous] ? MPRemoteCommandHandlerStatusSuccess : MPRemoteCommandHandlerStatusNoSuchContent;
  862. } else if (event.command == cc.skipForwardCommand) {
  863. if ([event isKindOfClass:[MPSkipIntervalCommandEvent class]]) {
  864. MPSkipIntervalCommandEvent *skipEvent = (MPSkipIntervalCommandEvent *)event;
  865. [_mediaPlayer jumpForward:skipEvent.interval];
  866. } else {
  867. result = MPRemoteCommandHandlerStatusCommandFailed;
  868. }
  869. } else if (event.command == cc.skipBackwardCommand) {
  870. if ([event isKindOfClass:[MPSkipIntervalCommandEvent class]]) {
  871. MPSkipIntervalCommandEvent *skipEvent = (MPSkipIntervalCommandEvent *)event;
  872. [_mediaPlayer jumpBackward:skipEvent.interval];
  873. } else {
  874. result = MPRemoteCommandHandlerStatusCommandFailed;
  875. }
  876. } else if (event.command == cc.changePlaybackRateCommand) {
  877. if ([event isKindOfClass:[MPChangePlaybackRateCommandEvent class]]) {
  878. MPChangePlaybackRateCommandEvent *rateEvent = (MPChangePlaybackRateCommandEvent *)event;
  879. [_mediaPlayer setRate:rateEvent.playbackRate];
  880. } else {
  881. result = MPRemoteCommandHandlerStatusCommandFailed;
  882. }
  883. /* stubs for when we want to support the other available commands */
  884. // } else if (event.command == cc.seekForwardCommand) {
  885. // } else if (event.command == cc.seekBackwardCommand) {
  886. // } else if (event.command == cc.ratingCommand) {
  887. // } else if (event.command == cc.likeCommand) {
  888. // } else if (event.command == cc.dislikeCommand) {
  889. // } else if (event.command == cc.bookmarkCommand) {
  890. } else {
  891. APLog(@"%s Unsupported remote control event: %@",__PRETTY_FUNCTION__,event);
  892. result = MPRemoteCommandHandlerStatusCommandFailed;
  893. }
  894. if (result == MPRemoteCommandHandlerStatusCommandFailed)
  895. APLog(@"%s Wasn't able to handle remote control event: %@",__PRETTY_FUNCTION__,event);
  896. return result;
  897. }
  898. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  899. {
  900. switch (event.subtype) {
  901. case UIEventSubtypeRemoteControlPlay:
  902. [_listPlayer play];
  903. break;
  904. case UIEventSubtypeRemoteControlPause:
  905. [_listPlayer pause];
  906. break;
  907. case UIEventSubtypeRemoteControlTogglePlayPause:
  908. [self playPause];
  909. break;
  910. case UIEventSubtypeRemoteControlNextTrack:
  911. [self forward];
  912. break;
  913. case UIEventSubtypeRemoteControlPreviousTrack:
  914. [self backward];
  915. break;
  916. case UIEventSubtypeRemoteControlStop:
  917. [self stopPlayback];
  918. break;
  919. default:
  920. break;
  921. }
  922. }
  923. #pragma mark - background interaction
  924. - (void)applicationWillResignActive:(NSNotification *)aNotification
  925. {
  926. [self _savePlaybackState];
  927. _preBackgroundWrapperView = _videoOutputViewWrapper;
  928. [self setVideoOutputView:nil];
  929. if (_mediaPlayer.audioTrackIndexes.count > 0)
  930. _mediaPlayer.currentVideoTrackIndex = -1;
  931. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  932. if ([_mediaPlayer isPlaying]) {
  933. [_mediaPlayer pause];
  934. _shouldResumePlaying = YES;
  935. }
  936. }
  937. }
  938. - (void)applicationDidEnterBackground:(NSNotification *)notification
  939. {
  940. _shouldResumePlaying = NO;
  941. }
  942. - (void)applicationDidBecomeActive:(NSNotification *)notification
  943. {
  944. if (_preBackgroundWrapperView) {
  945. [self setVideoOutputView:_preBackgroundWrapperView];
  946. _preBackgroundWrapperView = nil;
  947. }
  948. if (_mediaPlayer.numberOfVideoTracks > 0) {
  949. /* re-enable video decoding */
  950. _mediaPlayer.currentVideoTrackIndex = 1;
  951. }
  952. if (_shouldResumePlaying) {
  953. _shouldResumePlaying = NO;
  954. [_listPlayer play];
  955. }
  956. }
  957. #pragma mark - helpers
  958. - (NSString *)_resolveFontName
  959. {
  960. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  961. BOOL bold = [[defaults objectForKey:kVLCSettingSubtitlesBoldFont] boolValue];
  962. NSString *font = [defaults objectForKey:kVLCSettingSubtitlesFont];
  963. NSDictionary *fontMap = @{
  964. @"AmericanTypewriter": @"AmericanTypewriter-Bold",
  965. @"ArialMT": @"Arial-BoldMT",
  966. @"ArialHebrew": @"ArialHebrew-Bold",
  967. @"ChalkboardSE-Regular": @"ChalkboardSE-Bold",
  968. @"CourierNewPSMT": @"CourierNewPS-BoldMT",
  969. @"Georgia": @"Georgia-Bold",
  970. @"GillSans": @"GillSans-Bold",
  971. @"GujaratiSangamMN": @"GujaratiSangamMN-Bold",
  972. @"STHeitiSC-Light": @"STHeitiSC-Medium",
  973. @"STHeitiTC-Light": @"STHeitiTC-Medium",
  974. @"HelveticaNeue": @"HelveticaNeue-Bold",
  975. @"HiraKakuProN-W3": @"HiraKakuProN-W6",
  976. @"HiraMinProN-W3": @"HiraMinProN-W6",
  977. @"HoeflerText-Regular": @"HoeflerText-Black",
  978. @"Kailasa": @"Kailasa-Bold",
  979. @"KannadaSangamMN": @"KannadaSangamMN-Bold",
  980. @"MalayalamSangamMN": @"MalayalamSangamMN-Bold",
  981. @"OriyaSangamMN": @"OriyaSangamMN-Bold",
  982. @"SinhalaSangamMN": @"SinhalaSangamMN-Bold",
  983. @"SnellRoundhand": @"SnellRoundhand-Bold",
  984. @"TamilSangamMN": @"TamilSangamMN-Bold",
  985. @"TeluguSangamMN": @"TeluguSangamMN-Bold",
  986. @"TimesNewRomanPSMT": @"TimesNewRomanPS-BoldMT",
  987. @"Zapfino": @"Zapfino"
  988. };
  989. if (!bold) {
  990. return font;
  991. } else {
  992. return fontMap[font];
  993. }
  994. }
  995. @end