VLCPlaybackController.m 42 KB

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