VLCPlaybackController.m 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  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 = NO;
  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. } else {
  639. NSDictionary * metaDict = _mediaPlayer.media.metaDictionary;
  640. if (metaDict) {
  641. title = metaDict[VLCMetaInformationNowPlaying] ? metaDict[VLCMetaInformationNowPlaying] : metaDict[VLCMetaInformationTitle];
  642. artist = metaDict[VLCMetaInformationArtist];
  643. albumName = metaDict[VLCMetaInformationAlbum];
  644. trackNumber = metaDict[VLCMetaInformationTrackNumber];
  645. }
  646. }
  647. if (!mediaIsAudioOnly) {
  648. /* either what we are playing is not a file known to MLKit or
  649. * MLKit fails to acknowledge that it is audio-only.
  650. * Either way, do a more expensive check to see if it is really audio-only */
  651. NSArray *tracks = _mediaPlayer.media.tracksInformation;
  652. NSUInteger trackCount = tracks.count;
  653. mediaIsAudioOnly = YES;
  654. for (NSUInteger x = 0 ; x < trackCount; x++) {
  655. if ([[tracks[x] objectForKey:VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  656. mediaIsAudioOnly = NO;
  657. break;
  658. }
  659. }
  660. }
  661. if (mediaIsAudioOnly) {
  662. artworkImage = [VLCThumbnailsCache thumbnailForManagedObject:item];
  663. if (artworkImage) {
  664. if (artist)
  665. title = [title stringByAppendingFormat:@" — %@", artist];
  666. if (albumName)
  667. title = [title stringByAppendingFormat:@" — %@", albumName];
  668. }
  669. if (title.length < 1)
  670. title = [[_mediaPlayer.media url] lastPathComponent];
  671. }
  672. /* populate delegate with metadata info */
  673. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:title:artwork:artist:album:audioOnly:)])
  674. [self.delegate displayMetadataForPlaybackController:self
  675. title:title
  676. artwork:artworkImage
  677. artist:artist
  678. album:albumName
  679. audioOnly:mediaIsAudioOnly];
  680. /* populate now playing info center with metadata information */
  681. NSMutableDictionary *currentlyPlayingTrackInfo = [NSMutableDictionary dictionary];
  682. currentlyPlayingTrackInfo[MPMediaItemPropertyPlaybackDuration] = @(_mediaPlayer.media.length.intValue / 1000.);
  683. currentlyPlayingTrackInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = @(_mediaPlayer.time.intValue / 1000.);
  684. currentlyPlayingTrackInfo[MPNowPlayingInfoPropertyPlaybackRate] = @(_mediaPlayer.isPlaying ? _mediaPlayer.rate : 0.0);
  685. /* don't leak sensitive information to the OS, if passcode lock is enabled */
  686. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingPasscodeOnKey] boolValue]) {
  687. if (title)
  688. currentlyPlayingTrackInfo[MPMediaItemPropertyTitle] = title;
  689. if (artist.length > 0)
  690. currentlyPlayingTrackInfo[MPMediaItemPropertyArtist] = artist;
  691. if (albumName.length > 0)
  692. currentlyPlayingTrackInfo[MPMediaItemPropertyAlbumTitle] = albumName;
  693. if ([trackNumber intValue] > 0)
  694. currentlyPlayingTrackInfo[MPMediaItemPropertyAlbumTrackNumber] = trackNumber;
  695. /* FIXME: UGLY HACK
  696. * iOS 8.2 and 8.3 include an issue which will lead to a termination of the client app if we set artwork
  697. * when the playback initialized through the watch extension
  698. * radar://pending */
  699. if ([WKInterfaceDevice class] != nil) {
  700. if ([WKInterfaceDevice currentDevice] != nil)
  701. goto setstuff;
  702. }
  703. if (artworkImage) {
  704. MPMediaItemArtwork *mpartwork = [[MPMediaItemArtwork alloc] initWithImage:artworkImage];
  705. currentlyPlayingTrackInfo[MPMediaItemPropertyArtwork] = mpartwork;
  706. }
  707. }
  708. setstuff:
  709. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = currentlyPlayingTrackInfo;
  710. [[NSNotificationCenter defaultCenter] postNotificationName:kVLCNotificationNowPlayingInfoUpdate object:self];
  711. _title = title;
  712. _artist = artist;
  713. _albumName = albumName;
  714. _artworkImage = artworkImage;
  715. _mediaIsAudioOnly = mediaIsAudioOnly;
  716. }
  717. - (void)recoverDisplayedMetadata
  718. {
  719. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:title:artwork:artist:album:audioOnly:)])
  720. [self.delegate displayMetadataForPlaybackController:self
  721. title:_title
  722. artwork:_artworkImage
  723. artist:_artist
  724. album:_albumName
  725. audioOnly:_mediaIsAudioOnly];
  726. }
  727. #pragma mark - remote events
  728. static inline NSArray * RemoteCommandCenterCommandsToHandle(MPRemoteCommandCenter *cc)
  729. {
  730. /* commmented out other available commands which we don't support now but may
  731. * support at some point in the future */
  732. return @[cc.pauseCommand, cc.playCommand, cc.stopCommand, cc.togglePlayPauseCommand,
  733. cc.nextTrackCommand, cc.previousTrackCommand,
  734. cc.skipForwardCommand, cc.skipBackwardCommand,
  735. // cc.seekForwardCommand, cc.seekBackwardCommand,
  736. // cc.ratingCommand,
  737. cc.changePlaybackRateCommand,
  738. // cc.likeCommand,cc.dislikeCommand,cc.bookmarkCommand,
  739. ];
  740. }
  741. - (void)subscribeRemoteCommands
  742. {
  743. /* pre iOS 7.1 */
  744. if (![MPRemoteCommandCenter class]) {
  745. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  746. return;
  747. }
  748. /* for iOS 7.1 and above: */
  749. MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
  750. /*
  751. * since the control center and lockscreen shows only either skipForward/Backward
  752. * or next/previousTrack buttons but prefers skip buttons,
  753. * we only enable skip buttons if we have a no medialist
  754. */
  755. BOOL enableSkip = [VLCPlaybackController sharedInstance].mediaList == nil;
  756. commandCenter.skipForwardCommand.enabled = enableSkip;
  757. commandCenter.skipBackwardCommand.enabled = enableSkip;
  758. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  759. NSNumber *forwardSkip = [defaults valueForKey:kVLCSettingPlaybackForwardSkipLength];
  760. commandCenter.skipForwardCommand.preferredIntervals = @[forwardSkip];
  761. NSNumber *backwardSkip = [defaults valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  762. commandCenter.skipBackwardCommand.preferredIntervals = @[backwardSkip];
  763. NSArray *supportedPlaybackRates = @[@(0.5),@(0.75),@(1.0),@(1.25),@(1.5),@(1.75),@(2.0)];
  764. commandCenter.changePlaybackRateCommand.supportedPlaybackRates = supportedPlaybackRates;
  765. NSArray *commandsToSubscribe = RemoteCommandCenterCommandsToHandle(commandCenter);
  766. for (MPRemoteCommand *command in commandsToSubscribe) {
  767. [command addTarget:self action:@selector(remoteCommandEvent:)];
  768. }
  769. }
  770. - (void)unsubscribeFromRemoteCommand
  771. {
  772. /* pre iOS 7.1 */
  773. if (![MPRemoteCommandCenter class]) {
  774. [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
  775. return;
  776. }
  777. /* for iOS 7.1 and above: */
  778. MPRemoteCommandCenter *cc = [MPRemoteCommandCenter sharedCommandCenter];
  779. NSArray *commmandsToRemoveFrom = RemoteCommandCenterCommandsToHandle(cc);
  780. for (MPRemoteCommand *command in commmandsToRemoveFrom) {
  781. [command removeTarget:self];
  782. }
  783. }
  784. - (MPRemoteCommandHandlerStatus )remoteCommandEvent:(MPRemoteCommandEvent *)event
  785. {
  786. MPRemoteCommandCenter *cc = [MPRemoteCommandCenter sharedCommandCenter];
  787. MPRemoteCommandHandlerStatus result = MPRemoteCommandHandlerStatusSuccess;
  788. if (event.command == cc.pauseCommand) {
  789. [_listPlayer pause];
  790. } else if (event.command == cc.playCommand) {
  791. [_listPlayer play];
  792. } else if (event.command == cc.stopCommand) {
  793. [_listPlayer stop];
  794. } else if (event.command == cc.togglePlayPauseCommand) {
  795. [self playPause];
  796. } else if (event.command == cc.nextTrackCommand) {
  797. result = [_listPlayer next] ? MPRemoteCommandHandlerStatusSuccess : MPRemoteCommandHandlerStatusNoSuchContent;
  798. } else if (event.command == cc.previousTrackCommand) {
  799. result = [_listPlayer previous] ? MPRemoteCommandHandlerStatusSuccess : MPRemoteCommandHandlerStatusNoSuchContent;
  800. } else if (event.command == cc.skipForwardCommand) {
  801. if ([event isKindOfClass:[MPSkipIntervalCommandEvent class]]) {
  802. MPSkipIntervalCommandEvent *skipEvent = (MPSkipIntervalCommandEvent *)event;
  803. [_mediaPlayer jumpForward:skipEvent.interval];
  804. } else {
  805. result = MPRemoteCommandHandlerStatusCommandFailed;
  806. }
  807. } else if (event.command == cc.skipBackwardCommand) {
  808. if ([event isKindOfClass:[MPSkipIntervalCommandEvent class]]) {
  809. MPSkipIntervalCommandEvent *skipEvent = (MPSkipIntervalCommandEvent *)event;
  810. [_mediaPlayer jumpBackward:skipEvent.interval];
  811. } else {
  812. result = MPRemoteCommandHandlerStatusCommandFailed;
  813. }
  814. } else if (event.command == cc.changePlaybackRateCommand) {
  815. if ([event isKindOfClass:[MPChangePlaybackRateCommandEvent class]]) {
  816. MPChangePlaybackRateCommandEvent *rateEvent = (MPChangePlaybackRateCommandEvent *)event;
  817. [_mediaPlayer setRate:rateEvent.playbackRate];
  818. } else {
  819. result = MPRemoteCommandHandlerStatusCommandFailed;
  820. }
  821. /* stubs for when we want to support the other available commands */
  822. // } else if (event.command == cc.seekForwardCommand) {
  823. // } else if (event.command == cc.seekBackwardCommand) {
  824. // } else if (event.command == cc.ratingCommand) {
  825. // } else if (event.command == cc.likeCommand) {
  826. // } else if (event.command == cc.dislikeCommand) {
  827. // } else if (event.command == cc.bookmarkCommand) {
  828. } else {
  829. APLog(@"%s Unsupported remote control event: %@",__PRETTY_FUNCTION__,event);
  830. result = MPRemoteCommandHandlerStatusCommandFailed;
  831. }
  832. if (result == MPRemoteCommandHandlerStatusCommandFailed)
  833. APLog(@"%s Wasn't able to handle remote control event: %@",__PRETTY_FUNCTION__,event);
  834. return result;
  835. }
  836. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  837. {
  838. switch (event.subtype) {
  839. case UIEventSubtypeRemoteControlPlay:
  840. [_listPlayer play];
  841. break;
  842. case UIEventSubtypeRemoteControlPause:
  843. [_listPlayer pause];
  844. break;
  845. case UIEventSubtypeRemoteControlTogglePlayPause:
  846. [self playPause];
  847. break;
  848. case UIEventSubtypeRemoteControlNextTrack:
  849. [self forward];
  850. break;
  851. case UIEventSubtypeRemoteControlPreviousTrack:
  852. [self backward];
  853. break;
  854. case UIEventSubtypeRemoteControlStop:
  855. [self stopPlayback];
  856. break;
  857. default:
  858. break;
  859. }
  860. }
  861. #pragma mark - background interaction
  862. - (void)applicationWillResignActive:(NSNotification *)aNotification
  863. {
  864. [self _savePlaybackState];
  865. _preBackgroundWrapperView = _videoOutputViewWrapper;
  866. [self setVideoOutputView:nil];
  867. if (_mediaPlayer.audioTrackIndexes.count > 0)
  868. _mediaPlayer.currentVideoTrackIndex = -1;
  869. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  870. if ([_mediaPlayer isPlaying]) {
  871. [_mediaPlayer pause];
  872. _shouldResumePlaying = YES;
  873. }
  874. }
  875. }
  876. - (void)applicationDidEnterBackground:(NSNotification *)notification
  877. {
  878. _shouldResumePlaying = NO;
  879. }
  880. - (void)applicationDidBecomeActive:(NSNotification *)notification
  881. {
  882. if (_preBackgroundWrapperView) {
  883. [self setVideoOutputView:_preBackgroundWrapperView];
  884. _preBackgroundWrapperView = nil;
  885. }
  886. if (_mediaPlayer.numberOfVideoTracks > 0) {
  887. /* re-enable video decoding and reset position once done */
  888. float position = _mediaPlayer.position;
  889. _mediaPlayer.currentVideoTrackIndex = 1;
  890. _mediaPlayer.position = position;
  891. }
  892. if (_shouldResumePlaying) {
  893. _shouldResumePlaying = NO;
  894. [_listPlayer play];
  895. }
  896. }
  897. #pragma mark - helpers
  898. - (NSString *)_resolveFontName
  899. {
  900. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  901. BOOL bold = [[defaults objectForKey:kVLCSettingSubtitlesBoldFont] boolValue];
  902. NSString *font = [defaults objectForKey:kVLCSettingSubtitlesFont];
  903. NSDictionary *fontMap = @{
  904. @"AmericanTypewriter": @"AmericanTypewriter-Bold",
  905. @"ArialMT": @"Arial-BoldMT",
  906. @"ArialHebrew": @"ArialHebrew-Bold",
  907. @"ChalkboardSE-Regular": @"ChalkboardSE-Bold",
  908. @"CourierNewPSMT": @"CourierNewPS-BoldMT",
  909. @"Georgia": @"Georgia-Bold",
  910. @"GillSans": @"GillSans-Bold",
  911. @"GujaratiSangamMN": @"GujaratiSangamMN-Bold",
  912. @"STHeitiSC-Light": @"STHeitiSC-Medium",
  913. @"STHeitiTC-Light": @"STHeitiTC-Medium",
  914. @"HelveticaNeue": @"HelveticaNeue-Bold",
  915. @"HiraKakuProN-W3": @"HiraKakuProN-W6",
  916. @"HiraMinProN-W3": @"HiraMinProN-W6",
  917. @"HoeflerText-Regular": @"HoeflerText-Black",
  918. @"Kailasa": @"Kailasa-Bold",
  919. @"KannadaSangamMN": @"KannadaSangamMN-Bold",
  920. @"MalayalamSangamMN": @"MalayalamSangamMN-Bold",
  921. @"OriyaSangamMN": @"OriyaSangamMN-Bold",
  922. @"SinhalaSangamMN": @"SinhalaSangamMN-Bold",
  923. @"SnellRoundhand": @"SnellRoundhand-Bold",
  924. @"TamilSangamMN": @"TamilSangamMN-Bold",
  925. @"TeluguSangamMN": @"TeluguSangamMN-Bold",
  926. @"TimesNewRomanPSMT": @"TimesNewRomanPS-BoldMT",
  927. @"Zapfino": @"Zapfino"
  928. };
  929. if (!bold) {
  930. return font;
  931. } else {
  932. return fontMap[font];
  933. }
  934. }
  935. @end