VLCPlaybackController.m 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  1. /*****************************************************************************
  2. * VLCPlaybackController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013-2015 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Felix Paul Kühne <fkuehne # videolan.org>
  9. * Carola Nitz <caro # videolan.org>
  10. * Gleb Pinigin <gpinigin # gmail.com>
  11. * Pierre Sagaspe <pierre.sagaspe # me.com>
  12. * Tobias Conradi <videolan # tobias-conradi.de>
  13. * Sylver Bruneau <sylver.bruneau # gmail dot com>
  14. * Winston Weinert <winston # ml1 dot net>
  15. *
  16. * Refer to the COPYING file of the official project for license.
  17. *****************************************************************************/
  18. #import "VLCPlaybackController.h"
  19. #import <CommonCrypto/CommonDigest.h>
  20. #import "UIDevice+VLC.h"
  21. #import <AVFoundation/AVFoundation.h>
  22. #import <MediaPlayer/MediaPlayer.h>
  23. #import "VLCThumbnailsCache.h"
  24. #import <WatchKit/WatchKit.h>
  25. #import "VLCAppDelegate.h"
  26. #import "VLCPlaylistViewController.h"
  27. @interface VLCPlaybackController () <AVAudioSessionDelegate, VLCMediaPlayerDelegate, VLCMediaDelegate>
  28. {
  29. BOOL _playerIsSetup;
  30. BOOL _playbackFailed;
  31. BOOL _shouldResumePlaying;
  32. NSArray *_aspectRatios;
  33. NSUInteger _currentAspectRatioMask;
  34. float _currentPlaybackRate;
  35. UIView *_videoOutputViewWrapper;
  36. UIView *_actualVideoOutputView;
  37. UIView *_preBackgroundWrapperView;
  38. /* cached stuff for the VC */
  39. NSString *_title;
  40. UIImage *_artworkImage;
  41. NSString *_artist;
  42. NSString *_albumName;
  43. BOOL _mediaIsAudioOnly;
  44. BOOL _needsMetadataUpdate;
  45. }
  46. @end
  47. @implementation VLCPlaybackController
  48. #pragma mark instance management
  49. + (VLCPlaybackController *)sharedInstance
  50. {
  51. static VLCPlaybackController *sharedInstance = nil;
  52. static dispatch_once_t pred;
  53. dispatch_once(&pred, ^{
  54. sharedInstance = [self new];
  55. });
  56. return sharedInstance;
  57. }
  58. - (void)dealloc
  59. {
  60. [[NSNotificationCenter defaultCenter] removeObserver:self];
  61. }
  62. #pragma mark - playback management
  63. - (BOOL)_blobCheck
  64. {
  65. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  66. NSString *directoryPath = searchPaths[0];
  67. if (![[NSFileManager defaultManager] fileExistsAtPath:[directoryPath stringByAppendingPathComponent:@"blob.bin"]])
  68. return NO;
  69. NSData *data = [NSData dataWithContentsOfFile:[directoryPath stringByAppendingPathComponent:@"blob.bin"]];
  70. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  71. CC_SHA1(data.bytes, (unsigned int)data.length, digest);
  72. NSMutableString *hash = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  73. for (unsigned int u = 0; u < CC_SHA1_DIGEST_LENGTH; u++)
  74. [hash appendFormat:@"%02x", digest[u]];
  75. if ([hash isEqualToString:kBlobHash])
  76. return YES;
  77. else
  78. return NO;
  79. }
  80. - (BOOL)_isMediaSuitableForDevice
  81. {
  82. if (!self.fileFromMediaLibrary)
  83. return YES;
  84. NSUInteger totalNumberOfPixels = [[[self.fileFromMediaLibrary videoTrack] valueForKey:@"width"] doubleValue] * [[[self.fileFromMediaLibrary videoTrack] valueForKey:@"height"] doubleValue];
  85. NSInteger speedCategory = [[UIDevice currentDevice] speedCategory];
  86. if (speedCategory == 1) {
  87. // iPhone 3GS, iPhone 4, first gen. iPad, 3rd and 4th generation iPod touch
  88. return (totalNumberOfPixels < 600000); // between 480p and 720p
  89. } else if (speedCategory == 2) {
  90. // iPhone 4S, iPad 2 and 3, iPod 4 and 5
  91. return (totalNumberOfPixels < 922000); // 720p
  92. } else if (speedCategory == 3) {
  93. // iPhone 5, iPad 4
  94. return (totalNumberOfPixels < 2074000); // 1080p
  95. } else if (speedCategory == 4) {
  96. // iPhone 6, 2014 iPads
  97. return (totalNumberOfPixels < 8850000); // 4K
  98. }
  99. return YES;
  100. }
  101. - (void)startPlayback
  102. {
  103. if (_playerIsSetup)
  104. return;
  105. [[AVAudioSession sharedInstance] setDelegate:self];
  106. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  107. [defaultCenter addObserver:self selector:@selector(audioSessionRouteChange:)
  108. name:AVAudioSessionRouteChangeNotification object:nil];
  109. [defaultCenter addObserver:self selector:@selector(applicationWillResignActive:)
  110. name:UIApplicationWillResignActiveNotification object:nil];
  111. [defaultCenter addObserver:self selector:@selector(applicationDidBecomeActive:)
  112. name:UIApplicationDidBecomeActiveNotification object:nil];
  113. [defaultCenter addObserver:self selector:@selector(applicationDidEnterBackground:)
  114. name:UIApplicationDidEnterBackgroundNotification object:nil];
  115. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  116. _aspectRatios = @[@"DEFAULT", @"FILL_TO_SCREEN", @"4:3", @"16:9", @"16:10", @"2.21:1"];
  117. if (!self.fileFromMediaLibrary && !self.url && !self.mediaList) {
  118. [self stopPlayback];
  119. return;
  120. }
  121. if (self.pathToExternalSubtitlesFile)
  122. _listPlayer = [[VLCMediaListPlayer alloc] initWithOptions:@[[NSString stringWithFormat:@"--%@=%@", kVLCSettingSubtitlesFilePath, self.pathToExternalSubtitlesFile]]];
  123. else
  124. _listPlayer = [[VLCMediaListPlayer alloc] init];
  125. /* video decoding permanently fails if we don't provide a UIView to draw into on init
  126. * hence we provide one which is not attached to any view controller for off-screen drawing
  127. * and disable video decoding once playback started */
  128. _actualVideoOutputView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
  129. _actualVideoOutputView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  130. _actualVideoOutputView.autoresizesSubviews = YES;
  131. _mediaPlayer = _listPlayer.mediaPlayer;
  132. [_mediaPlayer setDelegate:self];
  133. [_mediaPlayer setDrawable:_actualVideoOutputView];
  134. if ([[defaults objectForKey:kVLCSettingPlaybackSpeedDefaultValue] floatValue] != 0)
  135. [_mediaPlayer setRate: [[defaults objectForKey:kVLCSettingPlaybackSpeedDefaultValue] floatValue]];
  136. if ([[defaults objectForKey:kVLCSettingDeinterlace] intValue] != 0)
  137. [_mediaPlayer setDeinterlaceFilter:@"blend"];
  138. else
  139. [_mediaPlayer setDeinterlaceFilter:nil];
  140. if (self.pathToExternalSubtitlesFile)
  141. [_mediaPlayer openVideoSubTitlesFromFile:self.pathToExternalSubtitlesFile];
  142. VLCMedia *media;
  143. MLFile *item = self.fileFromMediaLibrary;
  144. if (item) {
  145. media = [VLCMedia mediaWithURL:item.url];
  146. media.delegate = self;
  147. } else if (self.mediaList) {
  148. media = [self.mediaList mediaAtIndex:self.itemInMediaListToBePlayedFirst];
  149. media.delegate = self;
  150. } else {
  151. media = [VLCMedia mediaWithURL:self.url];
  152. media.delegate = self;
  153. [media parse];
  154. }
  155. NSMutableDictionary *mediaDictionary = [[NSMutableDictionary alloc] init];
  156. [mediaDictionary setObject:[defaults objectForKey:kVLCSettingNetworkCaching] forKey:kVLCSettingNetworkCaching];
  157. [mediaDictionary setObject:[[defaults objectForKey:kVLCSettingStretchAudio] boolValue] ? kVLCSettingStretchAudioOnValue : kVLCSettingStretchAudioOffValue forKey:kVLCSettingStretchAudio];
  158. [mediaDictionary setObject:[defaults objectForKey:kVLCSettingTextEncoding] forKey:kVLCSettingTextEncoding];
  159. [mediaDictionary setObject:[defaults objectForKey:kVLCSettingSkipLoopFilter] forKey:kVLCSettingSkipLoopFilter];
  160. #if 0
  161. [NSTimeZone resetSystemTimeZone];
  162. NSString *tzName = [[NSTimeZone systemTimeZone] name];
  163. 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"];
  164. if ([tzNames containsObject:tzName] || [[tzName stringByDeletingLastPathComponent] isEqualToString:@"US"]) {
  165. NSArray *tracksInfo = media.tracksInformation;
  166. for (NSUInteger x = 0; x < tracksInfo.count; x++) {
  167. if ([[tracksInfo[x] objectForKey:VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeAudio])
  168. {
  169. NSInteger fourcc = [[tracksInfo[x] objectForKey:VLCMediaTracksInformationCodec] integerValue];
  170. switch (fourcc) {
  171. case 540161377:
  172. case 1647457633:
  173. case 858612577:
  174. case 862151027:
  175. case 862151013:
  176. case 1684566644:
  177. case 2126701:
  178. {
  179. if (![self _blobCheck]) {
  180. [mediaDictionary setObject:[NSNull null] forKey:@"no-audio"];
  181. APLog(@"audio playback disabled because an unsupported codec was found");
  182. }
  183. break;
  184. }
  185. default:
  186. break;
  187. }
  188. }
  189. }
  190. }
  191. #endif
  192. if (self.mediaList) {
  193. VLCMediaList *list = self.mediaList;
  194. NSUInteger count = list.count;
  195. for (NSUInteger x = 0; x < count; x++)
  196. [[list mediaAtIndex:x] addOptions:mediaDictionary];
  197. [_listPlayer setMediaList:self.mediaList];
  198. } else {
  199. [media addOptions:mediaDictionary];
  200. [_listPlayer setRootMedia:media];
  201. }
  202. [_listPlayer setRepeatMode:VLCDoNotRepeat];
  203. if (![self _isMediaSuitableForDevice]) {
  204. 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];
  205. [alert show];
  206. } else
  207. [self _playNewMedia];
  208. }
  209. - (void)_playNewMedia
  210. {
  211. NSNumber *playbackPositionInTime = @(0);
  212. CGFloat lastPosition = .0;
  213. NSInteger duration = 0;
  214. MLFile *matchedFile;
  215. // Set last selected equalizer profile
  216. unsigned int profile = (unsigned int)[[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingEqualizerProfile] integerValue];
  217. [_mediaPlayer resetEqualizerFromProfile:profile];
  218. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  219. if (self.fileFromMediaLibrary)
  220. matchedFile = self.fileFromMediaLibrary;
  221. else if (self.mediaList) {
  222. NSURL *url = [self.mediaList mediaAtIndex:self.itemInMediaListToBePlayedFirst].url;
  223. NSArray *files = [MLFile fileForURL:url];
  224. matchedFile = files.firstObject;
  225. }
  226. if (matchedFile.lastPosition) {
  227. lastPosition = matchedFile.lastPosition.floatValue;
  228. }
  229. duration = matchedFile.duration.intValue;
  230. if (lastPosition < .95) {
  231. if (duration != 0)
  232. playbackPositionInTime = @(lastPosition * (duration / 1000.));
  233. }
  234. if (playbackPositionInTime.intValue > 0 && (duration * lastPosition - duration) < -60000) {
  235. [_mediaPlayer.media addOptions:@{@"start-time": playbackPositionInTime}];
  236. APLog(@"set starttime to %i", playbackPositionInTime.intValue);
  237. }
  238. [_mediaPlayer addObserver:self forKeyPath:@"time" options:0 context:nil];
  239. [_mediaPlayer addObserver:self forKeyPath:@"remainingTime" options:0 context:nil];
  240. if (self.mediaList)
  241. [_listPlayer playItemAtIndex:self.itemInMediaListToBePlayedFirst];
  242. else
  243. [_listPlayer playMedia:_listPlayer.rootMedia];
  244. if (matchedFile) {
  245. if (matchedFile.lastAudioTrack.intValue > 0)
  246. _mediaPlayer.currentAudioTrackIndex = matchedFile.lastAudioTrack.intValue;
  247. if (matchedFile.lastSubtitleTrack.intValue > 0)
  248. _mediaPlayer.currentVideoSubTitleIndex = matchedFile.lastSubtitleTrack.intValue;
  249. }
  250. if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  251. [self.delegate prepareForMediaPlayback:self];
  252. _currentAspectRatioMask = 0;
  253. _mediaPlayer.videoAspectRatio = NULL;
  254. /* some demuxers don't respect :start-time, so re-try here */
  255. if (lastPosition < .95 && _mediaPlayer.position < lastPosition && (duration * lastPosition - duration) < -60000)
  256. _mediaPlayer.position = lastPosition;
  257. [self subscribeRemoteCommands];
  258. [[(VLCAppDelegate *)[UIApplication sharedApplication].delegate playlistViewController] displayMiniPlaybackViewIfNeeded];
  259. _playerIsSetup = YES;
  260. }
  261. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  262. {
  263. if (buttonIndex == 1)
  264. [self _playNewMedia];
  265. else {
  266. [self stopPlayback];
  267. }
  268. }
  269. - (void)stopPlayback
  270. {
  271. if (_mediaPlayer) {
  272. @try {
  273. [_mediaPlayer removeObserver:self forKeyPath:@"time"];
  274. [_mediaPlayer removeObserver:self forKeyPath:@"remainingTime"];
  275. }
  276. @catch (NSException *exception) {
  277. APLog(@"we weren't an observer yet");
  278. }
  279. if (_mediaPlayer.media) {
  280. [_mediaPlayer pause];
  281. [self _savePlaybackState];
  282. [_mediaPlayer stop];
  283. }
  284. if (_mediaPlayer)
  285. _mediaPlayer = nil;
  286. if (_listPlayer)
  287. _listPlayer = nil;
  288. }
  289. if (_fileFromMediaLibrary)
  290. _fileFromMediaLibrary = nil;
  291. if (_mediaList)
  292. _mediaList = nil;
  293. if (_url)
  294. _url = nil;
  295. if (_pathToExternalSubtitlesFile) {
  296. NSFileManager *fileManager = [NSFileManager defaultManager];
  297. if ([fileManager fileExistsAtPath:_pathToExternalSubtitlesFile])
  298. [fileManager removeItemAtPath:_pathToExternalSubtitlesFile error:nil];
  299. _pathToExternalSubtitlesFile = nil;
  300. }
  301. _playerIsSetup = NO;
  302. if (self.errorCallback && _playbackFailed)
  303. [[UIApplication sharedApplication] openURL:self.errorCallback];
  304. else if (self.successCallback)
  305. [[UIApplication sharedApplication] openURL:self.successCallback];
  306. if ([self.delegate respondsToSelector:@selector(presentingViewControllerShouldBeClosed:)])
  307. [self.delegate presentingViewControllerShouldBeClosed:self];
  308. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = nil;
  309. [self unsubscribeFromRemoteCommand];
  310. }
  311. - (void)_savePlaybackState
  312. {
  313. if (self.fileFromMediaLibrary) {
  314. @try {
  315. MLFile *item = self.fileFromMediaLibrary;
  316. item.lastPosition = @([_mediaPlayer position]);
  317. item.lastAudioTrack = @(_mediaPlayer.currentAudioTrackIndex);
  318. item.lastSubtitleTrack = @(_mediaPlayer.currentVideoSubTitleIndex);
  319. }
  320. @catch (NSException *exception) {
  321. APLog(@"failed to save current media state - file removed?");
  322. }
  323. } else {
  324. NSArray *files = [MLFile fileForURL:_mediaPlayer.media.url];
  325. if (files.count > 0) {
  326. MLFile *fileFromList = files.firstObject;
  327. fileFromList.lastPosition = @([_mediaPlayer position]);
  328. fileFromList.lastAudioTrack = @(_mediaPlayer.currentAudioTrackIndex);
  329. fileFromList.lastSubtitleTrack = @(_mediaPlayer.currentVideoSubTitleIndex);
  330. }
  331. }
  332. }
  333. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
  334. {
  335. if ([self.delegate respondsToSelector:@selector(playbackPositionUpdated:)])
  336. [self.delegate playbackPositionUpdated:self];
  337. }
  338. - (NSInteger)mediaDuration
  339. {
  340. return _listPlayer.mediaPlayer.media.length.intValue;;
  341. }
  342. - (BOOL)isPlaying
  343. {
  344. return _mediaPlayer.isPlaying;
  345. }
  346. - (VLCRepeatMode)repeatMode
  347. {
  348. return _listPlayer.repeatMode;
  349. }
  350. - (void)setRepeatMode:(VLCRepeatMode)repeatMode
  351. {
  352. _listPlayer.repeatMode = repeatMode;
  353. }
  354. - (BOOL)currentMediaHasChapters
  355. {
  356. return [_mediaPlayer countOfTitles] > 1 || [_mediaPlayer chaptersForTitleIndex:_mediaPlayer.currentTitleIndex].count > 1;
  357. }
  358. - (BOOL)currentMediaHasTrackToChooseFrom
  359. {
  360. return [[_mediaPlayer audioTrackIndexes] count] > 2 || [[_mediaPlayer videoSubTitlesIndexes] count] > 1;
  361. }
  362. - (BOOL)activePlaybackSession
  363. {
  364. return _mediaPlayer != nil;
  365. }
  366. - (BOOL)audioOnlyPlaybackSession
  367. {
  368. return _mediaIsAudioOnly;
  369. }
  370. - (float)playbackRate
  371. {
  372. float f_rate = _mediaPlayer.rate;
  373. double value = 17 * log(f_rate) / log(2.);
  374. float returnValue = (int) ((value > 0) ? value + .5 : value - .5);
  375. if (returnValue < -34.)
  376. returnValue = -34.;
  377. else if (returnValue > 34.)
  378. returnValue = 34.;
  379. _currentPlaybackRate = returnValue;
  380. return returnValue;
  381. }
  382. - (void)setPlaybackRate:(float)playbackRate
  383. {
  384. if (_currentPlaybackRate != playbackRate)
  385. [_mediaPlayer setRate:playbackRate];
  386. _currentPlaybackRate = playbackRate;
  387. }
  388. - (void)mediaPlayerStateChanged:(NSNotification *)aNotification
  389. {
  390. VLCMediaPlayerState currentState = _mediaPlayer.state;
  391. if (currentState == VLCMediaPlayerStateBuffering) {
  392. /* attach delegate */
  393. _mediaPlayer.media.delegate = self;
  394. /* on-the-fly values through hidden API */
  395. [_mediaPlayer performSelector:@selector(setTextRendererFont:) withObject:[self _resolveFontName]];
  396. [_mediaPlayer performSelector:@selector(setTextRendererFontSize:) withObject:[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingSubtitlesFontSize]];
  397. [_mediaPlayer performSelector:@selector(setTextRendererFontColor:) withObject:[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingSubtitlesFontColor]];
  398. } else if (currentState == VLCMediaPlayerStateError) {
  399. _playbackFailed = YES;
  400. if ([self.delegate respondsToSelector:@selector(presentingViewControllerShouldBeClosedAfterADelay:)])
  401. [self.delegate presentingViewControllerShouldBeClosedAfterADelay:self];
  402. [self stopPlayback];
  403. } else if ((currentState == VLCMediaPlayerStateEnded || currentState == VLCMediaPlayerStateStopped) && _listPlayer.repeatMode == VLCDoNotRepeat) {
  404. if ([_listPlayer.mediaList indexOfMedia:_mediaPlayer.media] == _listPlayer.mediaList.count - 1) {
  405. if ([self.delegate respondsToSelector:@selector(presentingViewControllerShouldBeClosedAfterADelay:)])
  406. [self.delegate presentingViewControllerShouldBeClosedAfterADelay:self];
  407. [self stopPlayback];
  408. return;
  409. }
  410. } else {
  411. /* disable video decoding if we have no place to show */
  412. if (_mediaPlayer.audioTrackIndexes.count > 0) {
  413. if (_videoOutputViewWrapper == nil)
  414. _mediaPlayer.currentVideoTrackIndex = -1;
  415. }
  416. }
  417. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  418. [self.delegate mediaPlayerStateChanged:currentState
  419. isPlaying:_mediaPlayer.isPlaying
  420. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  421. currentMediaHasChapters:self.currentMediaHasChapters
  422. forPlaybackController:self];
  423. [self setNeedsMetadataUpdate];
  424. }
  425. #pragma mark - playback controls
  426. - (void)playPause
  427. {
  428. if ([_mediaPlayer isPlaying])
  429. [_listPlayer pause];
  430. else
  431. [_listPlayer play];
  432. }
  433. - (void)forward
  434. {
  435. if (_mediaList) {
  436. [_listPlayer next];
  437. } else {
  438. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackForwardSkipLength];
  439. [_mediaPlayer jumpForward:skipLength.intValue];
  440. }
  441. }
  442. - (void)backward
  443. {
  444. if (_mediaList) {
  445. [_listPlayer previous];
  446. }
  447. else {
  448. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  449. [_mediaPlayer jumpBackward:skipLength.intValue];
  450. }
  451. }
  452. - (void)switchAspectRatio
  453. {
  454. NSUInteger count = [_aspectRatios count];
  455. if (_currentAspectRatioMask + 1 > count - 1) {
  456. _mediaPlayer.videoAspectRatio = NULL;
  457. _mediaPlayer.videoCropGeometry = NULL;
  458. _currentAspectRatioMask = 0;
  459. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  460. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), NSLocalizedString(@"DEFAULT", nil)] forPlaybackController:self];
  461. } else {
  462. _currentAspectRatioMask++;
  463. if ([_aspectRatios[_currentAspectRatioMask] isEqualToString:@"FILL_TO_SCREEN"]) {
  464. UIScreen *screen;
  465. if (![[UIDevice currentDevice] hasExternalDisplay])
  466. screen = [UIScreen mainScreen];
  467. else
  468. screen = [UIScreen screens][1];
  469. float f_ar = screen.bounds.size.width / screen.bounds.size.height;
  470. if (f_ar == (float)(640./1136.)) // iPhone 5 aka 16:9.01
  471. _mediaPlayer.videoCropGeometry = "16:9";
  472. else if (f_ar == (float)(2./3.)) // all other iPhones
  473. _mediaPlayer.videoCropGeometry = "16:10"; // libvlc doesn't support 2:3 crop
  474. else if (f_ar == .75) // all iPads
  475. _mediaPlayer.videoCropGeometry = "4:3";
  476. else if (f_ar == .5625) // AirPlay
  477. _mediaPlayer.videoCropGeometry = "16:9";
  478. else
  479. APLog(@"unknown screen format %f, can't crop", f_ar);
  480. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  481. [self.delegate showStatusMessage:NSLocalizedString(@"FILL_TO_SCREEN", nil) forPlaybackController:self];
  482. return;
  483. }
  484. _mediaPlayer.videoCropGeometry = NULL;
  485. _mediaPlayer.videoAspectRatio = (char *)[_aspectRatios[_currentAspectRatioMask] UTF8String];
  486. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  487. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), _aspectRatios[_currentAspectRatioMask]] forPlaybackController:self];
  488. }
  489. }
  490. - (void)setVideoOutputView:(UIView *)videoOutputView
  491. {
  492. if (videoOutputView) {
  493. if ([_actualVideoOutputView superview] != nil)
  494. [_actualVideoOutputView removeFromSuperview];
  495. _mediaPlayer.currentVideoTrackIndex = 0;
  496. _actualVideoOutputView.frame = (CGRect){CGPointZero, videoOutputView.frame.size};
  497. [_actualVideoOutputView layoutSubviews];
  498. [_actualVideoOutputView updateConstraints];
  499. [videoOutputView addSubview:_actualVideoOutputView];
  500. } else {
  501. [_actualVideoOutputView removeFromSuperview];
  502. if (_mediaPlayer.audioTrackIndexes.count > 0)
  503. _mediaPlayer.currentVideoTrackIndex = -1;
  504. }
  505. _videoOutputViewWrapper = videoOutputView;
  506. }
  507. - (UIView *)videoOutputView
  508. {
  509. return _videoOutputViewWrapper;
  510. }
  511. #pragma mark - equalizer
  512. - (void)setAmplification:(CGFloat)amplification forBand:(unsigned int)index
  513. {
  514. if (!_mediaPlayer.equalizerEnabled)
  515. [_mediaPlayer setEqualizerEnabled:YES];
  516. [_mediaPlayer setAmplification:amplification forBand:index];
  517. // For some reason we have to apply again preamp to apply change
  518. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  519. }
  520. - (CGFloat)amplificationOfBand:(unsigned int)index
  521. {
  522. return [_mediaPlayer amplificationOfBand:index];
  523. }
  524. - (NSArray *)equalizerProfiles
  525. {
  526. return _mediaPlayer.equalizerProfiles;
  527. }
  528. - (void)resetEqualizerFromProfile:(unsigned int)profile
  529. {
  530. [[NSUserDefaults standardUserDefaults] setObject:@(profile) forKey:kVLCSettingEqualizerProfile];
  531. [_mediaPlayer resetEqualizerFromProfile:profile];
  532. }
  533. - (void)setPreAmplification:(CGFloat)preAmplification
  534. {
  535. if (!_mediaPlayer.equalizerEnabled)
  536. [_mediaPlayer setEqualizerEnabled:YES];
  537. [_mediaPlayer setPreAmplification:preAmplification];
  538. }
  539. - (CGFloat)preAmplification
  540. {
  541. return [_mediaPlayer preAmplification];
  542. }
  543. #pragma mark - AVSession delegate
  544. - (void)beginInterruption
  545. {
  546. if ([_mediaPlayer isPlaying]) {
  547. [_mediaPlayer pause];
  548. _shouldResumePlaying = YES;
  549. }
  550. }
  551. - (void)endInterruption
  552. {
  553. if (_shouldResumePlaying) {
  554. [_mediaPlayer play];
  555. _shouldResumePlaying = NO;
  556. }
  557. }
  558. - (void)audioSessionRouteChange:(NSNotification *)notification
  559. {
  560. NSArray *outputs = [[AVAudioSession sharedInstance] currentRoute].outputs;
  561. NSString *portName = [[outputs objectAtIndex:0] portName];
  562. if (![portName isEqualToString:@"Headphones"] && [_mediaPlayer isPlaying])
  563. [_listPlayer pause];
  564. }
  565. #pragma mark - Managing the media item
  566. - (void)setFileFromMediaLibrary:(MLFile *)fileFromMediaLibrary
  567. {
  568. if (_fileFromMediaLibrary != fileFromMediaLibrary) {
  569. [self stopPlayback];
  570. _fileFromMediaLibrary = fileFromMediaLibrary;
  571. }
  572. }
  573. - (void)setUrl:(NSURL *)url
  574. {
  575. [self stopPlayback];
  576. _url = url;
  577. _playerIsSetup = NO;
  578. }
  579. - (void)setMediaList:(VLCMediaList *)mediaList
  580. {
  581. [self stopPlayback];
  582. _mediaList = mediaList;
  583. _playerIsSetup = NO;
  584. }
  585. - (MLFile *)currentlyPlayingMediaFile {
  586. MLFile *mediaFile = self.fileFromMediaLibrary;
  587. if (mediaFile) {
  588. return mediaFile;
  589. } else if (self.mediaList) {
  590. NSArray *results = [MLFile fileForURL:_mediaPlayer.media.url];
  591. return results.firstObject;
  592. }
  593. return nil;
  594. }
  595. #pragma mark - metadata handling
  596. - (void)mediaDidFinishParsing:(VLCMedia *)aMedia
  597. {
  598. [self setNeedsMetadataUpdate];
  599. }
  600. - (void)mediaMetaDataDidChange:(VLCMedia*)aMedia
  601. {
  602. [self setNeedsMetadataUpdate];
  603. }
  604. - (void)setNeedsMetadataUpdate
  605. {
  606. if (_needsMetadataUpdate == NO) {
  607. _needsMetadataUpdate = YES;
  608. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  609. [self _updateDisplayedMetadata];
  610. });
  611. }
  612. }
  613. - (void)_updateDisplayedMetadata
  614. {
  615. _needsMetadataUpdate = NO;
  616. MLFile *item;
  617. NSNumber *trackNumber;
  618. NSString *title;
  619. NSString *artist;
  620. NSString *albumName;
  621. UIImage* artworkImage;
  622. BOOL mediaIsAudioOnly = YES;
  623. if (self.fileFromMediaLibrary)
  624. item = self.fileFromMediaLibrary;
  625. else if (self.mediaList) {
  626. NSArray *matches = [MLFile fileForURL:_mediaPlayer.media.url];
  627. item = matches.firstObject;
  628. }
  629. if (item) {
  630. if (item.isAlbumTrack) {
  631. title = item.albumTrack.title;
  632. artist = item.albumTrack.artist;
  633. albumName = item.albumTrack.album.name;
  634. } else
  635. title = item.title;
  636. /* MLKit knows better than us if this thing is audio only or not */
  637. mediaIsAudioOnly = [item isSupportedAudioFile];
  638. if (mediaIsAudioOnly)
  639. artworkImage = [VLCThumbnailsCache thumbnailForManagedObject:item];
  640. } else {
  641. NSDictionary * metaDict = _mediaPlayer.media.metaDictionary;
  642. /* this is a non file media, so we need to actually check if there is there is
  643. * a video track included or not */
  644. NSArray *tracks = _mediaPlayer.media.tracksInformation;
  645. NSUInteger trackCount = tracks.count;
  646. for (NSUInteger x = 0 ; x < trackCount; x++) {
  647. if ([[tracks[x] objectForKey:VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  648. mediaIsAudioOnly = NO;
  649. break;
  650. }
  651. }
  652. if (metaDict) {
  653. title = metaDict[VLCMetaInformationNowPlaying] ? metaDict[VLCMetaInformationNowPlaying] : metaDict[VLCMetaInformationTitle];
  654. artist = metaDict[VLCMetaInformationArtist];
  655. albumName = metaDict[VLCMetaInformationAlbum];
  656. trackNumber = metaDict[VLCMetaInformationTrackNumber];
  657. if (mediaIsAudioOnly)
  658. artworkImage = [VLCThumbnailsCache thumbnailForManagedObject:item];
  659. }
  660. }
  661. if (mediaIsAudioOnly) {
  662. if (artworkImage) {
  663. if (artist)
  664. title = [title stringByAppendingFormat:@" — %@", artist];
  665. if (albumName)
  666. title = [title stringByAppendingFormat:@" — %@", albumName];
  667. }
  668. if (title.length < 1)
  669. title = [[_mediaPlayer.media url] lastPathComponent];
  670. }
  671. /* populate delegate with metadata info */
  672. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:title:artwork:artist:album:audioOnly:)])
  673. [self.delegate displayMetadataForPlaybackController:self
  674. title:title
  675. artwork:artworkImage
  676. artist:artist
  677. album:albumName
  678. audioOnly:mediaIsAudioOnly];
  679. /* populate now playing info center with metadata information */
  680. NSMutableDictionary *currentlyPlayingTrackInfo = [NSMutableDictionary dictionary];
  681. currentlyPlayingTrackInfo[MPMediaItemPropertyPlaybackDuration] = @(_mediaPlayer.media.length.intValue / 1000.);
  682. currentlyPlayingTrackInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = @(_mediaPlayer.time.intValue / 1000.);
  683. currentlyPlayingTrackInfo[MPNowPlayingInfoPropertyPlaybackRate] = @(_mediaPlayer.isPlaying ? _mediaPlayer.rate : 0.0);
  684. /* don't leak sensitive information to the OS, if passcode lock is enabled */
  685. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingPasscodeOnKey] boolValue]) {
  686. if (title)
  687. currentlyPlayingTrackInfo[MPMediaItemPropertyTitle] = title;
  688. if (artist.length > 0)
  689. currentlyPlayingTrackInfo[MPMediaItemPropertyArtist] = artist;
  690. if (albumName.length > 0)
  691. currentlyPlayingTrackInfo[MPMediaItemPropertyAlbumTitle] = albumName;
  692. if ([trackNumber intValue] > 0)
  693. currentlyPlayingTrackInfo[MPMediaItemPropertyAlbumTrackNumber] = trackNumber;
  694. /* FIXME: UGLY HACK
  695. * iOS 8.2 and 8.3 include an issue which will lead to a termination of the client app if we set artwork
  696. * when the playback initialized through the watch extension
  697. * radar://pending */
  698. if ([WKInterfaceDevice class] != nil) {
  699. if ([WKInterfaceDevice currentDevice] != nil)
  700. goto setstuff;
  701. }
  702. if (artworkImage) {
  703. MPMediaItemArtwork *mpartwork = [[MPMediaItemArtwork alloc] initWithImage:artworkImage];
  704. currentlyPlayingTrackInfo[MPMediaItemPropertyArtwork] = mpartwork;
  705. }
  706. }
  707. setstuff:
  708. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = currentlyPlayingTrackInfo;
  709. [[NSNotificationCenter defaultCenter] postNotificationName:kVLCNotificationNowPlayingInfoUpdate object:self];
  710. _title = title;
  711. _artist = artist;
  712. _albumName = albumName;
  713. _artworkImage = artworkImage;
  714. _mediaIsAudioOnly = mediaIsAudioOnly;
  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. _preBackgroundWrapperView = _videoOutputViewWrapper;
  865. [self setVideoOutputView:nil];
  866. if (_mediaPlayer.audioTrackIndexes.count > 0)
  867. _mediaPlayer.currentVideoTrackIndex = -1;
  868. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  869. if ([_mediaPlayer isPlaying]) {
  870. [_mediaPlayer pause];
  871. _shouldResumePlaying = YES;
  872. }
  873. }
  874. }
  875. - (void)applicationDidEnterBackground:(NSNotification *)notification
  876. {
  877. _shouldResumePlaying = NO;
  878. }
  879. - (void)applicationDidBecomeActive:(NSNotification *)notification
  880. {
  881. if (_preBackgroundWrapperView) {
  882. [self setVideoOutputView:_preBackgroundWrapperView];
  883. _preBackgroundWrapperView = nil;
  884. }
  885. if (_mediaPlayer.numberOfVideoTracks > 0) {
  886. /* re-enable video decoding and reset position once done */
  887. float position = _mediaPlayer.position;
  888. _mediaPlayer.currentVideoTrackIndex = 1;
  889. _mediaPlayer.position = position;
  890. }
  891. if (_shouldResumePlaying) {
  892. _shouldResumePlaying = NO;
  893. [_listPlayer play];
  894. }
  895. }
  896. #pragma mark - helpers
  897. - (NSString *)_resolveFontName
  898. {
  899. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  900. BOOL bold = [[defaults objectForKey:kVLCSettingSubtitlesBoldFont] boolValue];
  901. NSString *font = [defaults objectForKey:kVLCSettingSubtitlesFont];
  902. NSDictionary *fontMap = @{
  903. @"AmericanTypewriter": @"AmericanTypewriter-Bold",
  904. @"ArialMT": @"Arial-BoldMT",
  905. @"ArialHebrew": @"ArialHebrew-Bold",
  906. @"ChalkboardSE-Regular": @"ChalkboardSE-Bold",
  907. @"CourierNewPSMT": @"CourierNewPS-BoldMT",
  908. @"Georgia": @"Georgia-Bold",
  909. @"GillSans": @"GillSans-Bold",
  910. @"GujaratiSangamMN": @"GujaratiSangamMN-Bold",
  911. @"STHeitiSC-Light": @"STHeitiSC-Medium",
  912. @"STHeitiTC-Light": @"STHeitiTC-Medium",
  913. @"HelveticaNeue": @"HelveticaNeue-Bold",
  914. @"HiraKakuProN-W3": @"HiraKakuProN-W6",
  915. @"HiraMinProN-W3": @"HiraMinProN-W6",
  916. @"HoeflerText-Regular": @"HoeflerText-Black",
  917. @"Kailasa": @"Kailasa-Bold",
  918. @"KannadaSangamMN": @"KannadaSangamMN-Bold",
  919. @"MalayalamSangamMN": @"MalayalamSangamMN-Bold",
  920. @"OriyaSangamMN": @"OriyaSangamMN-Bold",
  921. @"SinhalaSangamMN": @"SinhalaSangamMN-Bold",
  922. @"SnellRoundhand": @"SnellRoundhand-Bold",
  923. @"TamilSangamMN": @"TamilSangamMN-Bold",
  924. @"TeluguSangamMN": @"TeluguSangamMN-Bold",
  925. @"TimesNewRomanPSMT": @"TimesNewRomanPS-BoldMT",
  926. @"Zapfino": @"Zapfino"
  927. };
  928. if (!bold) {
  929. return font;
  930. } else {
  931. return fontMap[font];
  932. }
  933. }
  934. @end