VLCPlaybackController.m 42 KB

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