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