VLCPlaybackController.m 41 KB

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