VLCPlaybackController.m 42 KB

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