VLCPlaybackController.m 44 KB

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