VLCPlaybackController.m 45 KB

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