VLCPlaybackController.m 42 KB

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