VLCPlaybackController.m 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  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 ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
  246. [self.delegate prepareForMediaPlayback:self];
  247. _currentAspectRatioMask = 0;
  248. _mediaPlayer.videoAspectRatio = NULL;
  249. /* some demuxers don't respect :start-time, so re-try here */
  250. if (lastPosition < .95 && _mediaPlayer.position < lastPosition && (duration * lastPosition - duration) < -60000)
  251. _mediaPlayer.position = lastPosition;
  252. [self subscribeRemoteCommands];
  253. [[(VLCAppDelegate *)[UIApplication sharedApplication].delegate playlistViewController] displayMiniPlaybackViewIfNeeded];
  254. _playerIsSetup = YES;
  255. _mediaWasJustStarted = YES;
  256. }
  257. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  258. {
  259. if (buttonIndex == 1)
  260. [self _playNewMedia];
  261. else
  262. [self stopPlayback];
  263. }
  264. - (void)stopPlayback
  265. {
  266. if (_mediaPlayer) {
  267. @try {
  268. [_mediaPlayer removeObserver:self forKeyPath:@"time"];
  269. [_mediaPlayer removeObserver:self forKeyPath:@"remainingTime"];
  270. }
  271. @catch (NSException *exception) {
  272. APLog(@"we weren't an observer yet");
  273. }
  274. if (_mediaPlayer.media) {
  275. [_mediaPlayer pause];
  276. [self _savePlaybackState];
  277. [_mediaPlayer stop];
  278. }
  279. if (_mediaPlayer)
  280. _mediaPlayer = nil;
  281. if (_listPlayer)
  282. _listPlayer = nil;
  283. }
  284. if (_fileFromMediaLibrary)
  285. _fileFromMediaLibrary = nil;
  286. if (_mediaList)
  287. _mediaList = nil;
  288. if (_url)
  289. _url = nil;
  290. if (_pathToExternalSubtitlesFile) {
  291. NSFileManager *fileManager = [NSFileManager defaultManager];
  292. if ([fileManager fileExistsAtPath:_pathToExternalSubtitlesFile])
  293. [fileManager removeItemAtPath:_pathToExternalSubtitlesFile error:nil];
  294. _pathToExternalSubtitlesFile = nil;
  295. }
  296. _playerIsSetup = NO;
  297. if (self.errorCallback && _playbackFailed)
  298. [[UIApplication sharedApplication] openURL:self.errorCallback];
  299. else if (self.successCallback)
  300. [[UIApplication sharedApplication] openURL:self.successCallback];
  301. if ([self.delegate respondsToSelector:@selector(presentingViewControllerShouldBeClosed:)])
  302. [self.delegate presentingViewControllerShouldBeClosed:self];
  303. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = nil;
  304. [self unsubscribeFromRemoteCommand];
  305. }
  306. - (void)_savePlaybackState
  307. {
  308. if (self.fileFromMediaLibrary) {
  309. @try {
  310. MLFile *item = self.fileFromMediaLibrary;
  311. item.lastPosition = @([_mediaPlayer position]);
  312. item.lastAudioTrack = @(_mediaPlayer.currentAudioTrackIndex);
  313. item.lastSubtitleTrack = @(_mediaPlayer.currentVideoSubTitleIndex);
  314. }
  315. @catch (NSException *exception) {
  316. APLog(@"failed to save current media state - file removed?");
  317. }
  318. } else {
  319. NSArray *files = [MLFile fileForURL:_mediaPlayer.media.url];
  320. if (files.count > 0) {
  321. MLFile *fileFromList = files.firstObject;
  322. fileFromList.lastPosition = @([_mediaPlayer position]);
  323. fileFromList.lastAudioTrack = @(_mediaPlayer.currentAudioTrackIndex);
  324. fileFromList.lastSubtitleTrack = @(_mediaPlayer.currentVideoSubTitleIndex);
  325. }
  326. }
  327. }
  328. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
  329. {
  330. if ([self.delegate respondsToSelector:@selector(playbackPositionUpdated:)])
  331. [self.delegate playbackPositionUpdated:self];
  332. }
  333. - (NSInteger)mediaDuration
  334. {
  335. return _listPlayer.mediaPlayer.media.length.intValue;;
  336. }
  337. - (BOOL)isPlaying
  338. {
  339. return _mediaPlayer.isPlaying;
  340. }
  341. - (VLCRepeatMode)repeatMode
  342. {
  343. return _listPlayer.repeatMode;
  344. }
  345. - (void)setRepeatMode:(VLCRepeatMode)repeatMode
  346. {
  347. _listPlayer.repeatMode = repeatMode;
  348. }
  349. - (BOOL)currentMediaHasChapters
  350. {
  351. return [_mediaPlayer countOfTitles] > 1 || [_mediaPlayer chaptersForTitleIndex:_mediaPlayer.currentTitleIndex].count > 1;
  352. }
  353. - (BOOL)currentMediaHasTrackToChooseFrom
  354. {
  355. return [[_mediaPlayer audioTrackIndexes] count] > 2 || [[_mediaPlayer videoSubTitlesIndexes] count] > 1;
  356. }
  357. - (BOOL)activePlaybackSession
  358. {
  359. return _mediaPlayer != nil;
  360. }
  361. - (BOOL)audioOnlyPlaybackSession
  362. {
  363. return _mediaIsAudioOnly;
  364. }
  365. - (float)playbackRate
  366. {
  367. float f_rate = _mediaPlayer.rate;
  368. double value = 17 * log(f_rate) / log(2.);
  369. float returnValue = (int) ((value > 0) ? value + .5 : value - .5);
  370. if (returnValue < -34.)
  371. returnValue = -34.;
  372. else if (returnValue > 34.)
  373. returnValue = 34.;
  374. _currentPlaybackRate = returnValue;
  375. return returnValue;
  376. }
  377. - (void)setPlaybackRate:(float)playbackRate
  378. {
  379. if (_currentPlaybackRate != playbackRate)
  380. [_mediaPlayer setRate:playbackRate];
  381. _currentPlaybackRate = playbackRate;
  382. }
  383. - (void)mediaPlayerStateChanged:(NSNotification *)aNotification
  384. {
  385. VLCMediaPlayerState currentState = _mediaPlayer.state;
  386. if (currentState == VLCMediaPlayerStateBuffering) {
  387. /* attach delegate */
  388. _mediaPlayer.media.delegate = self;
  389. /* on-the-fly values through hidden API */
  390. [_mediaPlayer performSelector:@selector(setTextRendererFont:) withObject:[self _resolveFontName]];
  391. [_mediaPlayer performSelector:@selector(setTextRendererFontSize:) withObject:[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingSubtitlesFontSize]];
  392. [_mediaPlayer performSelector:@selector(setTextRendererFontColor:) withObject:[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingSubtitlesFontColor]];
  393. } else if (currentState == VLCMediaPlayerStateError) {
  394. _playbackFailed = YES;
  395. if ([self.delegate respondsToSelector:@selector(presentingViewControllerShouldBeClosedAfterADelay:)])
  396. [self.delegate presentingViewControllerShouldBeClosedAfterADelay:self];
  397. [self stopPlayback];
  398. } else if ((currentState == VLCMediaPlayerStateEnded || currentState == VLCMediaPlayerStateStopped) && _listPlayer.repeatMode == VLCDoNotRepeat) {
  399. if ([_listPlayer.mediaList indexOfMedia:_mediaPlayer.media] == _listPlayer.mediaList.count - 1) {
  400. if ([self.delegate respondsToSelector:@selector(presentingViewControllerShouldBeClosed:)])
  401. [self.delegate presentingViewControllerShouldBeClosed:self];
  402. [self stopPlayback];
  403. return;
  404. }
  405. } else {
  406. /* disable video decoding if we have no place to show */
  407. if (_mediaPlayer.numberOfAudioTracks > 0) {
  408. if (_videoOutputViewWrapper == nil)
  409. _mediaPlayer.currentVideoTrackIndex = -1;
  410. }
  411. }
  412. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  413. [self.delegate mediaPlayerStateChanged:currentState
  414. isPlaying:_mediaPlayer.isPlaying
  415. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  416. currentMediaHasChapters:self.currentMediaHasChapters
  417. forPlaybackController:self];
  418. [self setNeedsMetadataUpdate];
  419. }
  420. #pragma mark - playback controls
  421. - (void)playPause
  422. {
  423. if ([_mediaPlayer isPlaying])
  424. [_listPlayer pause];
  425. else
  426. [_listPlayer play];
  427. }
  428. - (void)forward
  429. {
  430. if (_mediaList) {
  431. [_listPlayer next];
  432. } else {
  433. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackForwardSkipLength];
  434. [_mediaPlayer jumpForward:skipLength.intValue];
  435. }
  436. }
  437. - (void)backward
  438. {
  439. if (_mediaList) {
  440. [_listPlayer previous];
  441. }
  442. else {
  443. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  444. [_mediaPlayer jumpBackward:skipLength.intValue];
  445. }
  446. }
  447. - (void)switchAspectRatio
  448. {
  449. NSUInteger count = [_aspectRatios count];
  450. if (_currentAspectRatioMask + 1 > count - 1) {
  451. _mediaPlayer.videoAspectRatio = NULL;
  452. _mediaPlayer.videoCropGeometry = NULL;
  453. _currentAspectRatioMask = 0;
  454. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  455. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), NSLocalizedString(@"DEFAULT", nil)] forPlaybackController:self];
  456. } else {
  457. _currentAspectRatioMask++;
  458. if ([_aspectRatios[_currentAspectRatioMask] isEqualToString:@"FILL_TO_SCREEN"]) {
  459. UIScreen *screen;
  460. if (![[UIDevice currentDevice] hasExternalDisplay])
  461. screen = [UIScreen mainScreen];
  462. else
  463. screen = [UIScreen screens][1];
  464. float f_ar = screen.bounds.size.width / screen.bounds.size.height;
  465. if (f_ar == (float)(640./1136.)) // iPhone 5 aka 16:9.01
  466. _mediaPlayer.videoCropGeometry = "16:9";
  467. else if (f_ar == (float)(2./3.)) // all other iPhones
  468. _mediaPlayer.videoCropGeometry = "16:10"; // libvlc doesn't support 2:3 crop
  469. else if (f_ar == .75) // all iPads
  470. _mediaPlayer.videoCropGeometry = "4:3";
  471. else if (f_ar == .5625) // AirPlay
  472. _mediaPlayer.videoCropGeometry = "16:9";
  473. else
  474. APLog(@"unknown screen format %f, can't crop", f_ar);
  475. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  476. [self.delegate showStatusMessage:NSLocalizedString(@"FILL_TO_SCREEN", nil) forPlaybackController:self];
  477. return;
  478. }
  479. _mediaPlayer.videoCropGeometry = NULL;
  480. _mediaPlayer.videoAspectRatio = (char *)[_aspectRatios[_currentAspectRatioMask] UTF8String];
  481. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  482. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), _aspectRatios[_currentAspectRatioMask]] forPlaybackController:self];
  483. }
  484. }
  485. - (void)setVideoOutputView:(UIView *)videoOutputView
  486. {
  487. if (videoOutputView) {
  488. if ([_actualVideoOutputView superview] != nil)
  489. [_actualVideoOutputView removeFromSuperview];
  490. _actualVideoOutputView.frame = (CGRect){CGPointZero, videoOutputView.frame.size};
  491. [_actualVideoOutputView layoutSubviews];
  492. [_actualVideoOutputView updateConstraints];
  493. if (_mediaPlayer.currentVideoTrackIndex == -1)
  494. _mediaPlayer.currentVideoTrackIndex = 0;
  495. [videoOutputView addSubview:_actualVideoOutputView];
  496. } else
  497. [_actualVideoOutputView removeFromSuperview];
  498. _videoOutputViewWrapper = videoOutputView;
  499. }
  500. - (UIView *)videoOutputView
  501. {
  502. return _videoOutputViewWrapper;
  503. }
  504. #pragma mark - equalizer
  505. - (void)setAmplification:(CGFloat)amplification forBand:(unsigned int)index
  506. {
  507. if (!_mediaPlayer.equalizerEnabled)
  508. [_mediaPlayer setEqualizerEnabled:YES];
  509. [_mediaPlayer setAmplification:amplification forBand:index];
  510. // For some reason we have to apply again preamp to apply change
  511. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  512. }
  513. - (CGFloat)amplificationOfBand:(unsigned int)index
  514. {
  515. return [_mediaPlayer amplificationOfBand:index];
  516. }
  517. - (NSArray *)equalizerProfiles
  518. {
  519. return _mediaPlayer.equalizerProfiles;
  520. }
  521. - (void)resetEqualizerFromProfile:(unsigned int)profile
  522. {
  523. [[NSUserDefaults standardUserDefaults] setObject:@(profile) forKey:kVLCSettingEqualizerProfile];
  524. [_mediaPlayer resetEqualizerFromProfile:profile];
  525. }
  526. - (void)setPreAmplification:(CGFloat)preAmplification
  527. {
  528. if (!_mediaPlayer.equalizerEnabled)
  529. [_mediaPlayer setEqualizerEnabled:YES];
  530. [_mediaPlayer setPreAmplification:preAmplification];
  531. }
  532. - (CGFloat)preAmplification
  533. {
  534. return [_mediaPlayer preAmplification];
  535. }
  536. #pragma mark - AVSession delegate
  537. - (void)beginInterruption
  538. {
  539. if ([_mediaPlayer isPlaying]) {
  540. [_mediaPlayer pause];
  541. _shouldResumePlaying = YES;
  542. }
  543. }
  544. - (void)endInterruption
  545. {
  546. if (_shouldResumePlaying) {
  547. [_mediaPlayer play];
  548. _shouldResumePlaying = NO;
  549. }
  550. }
  551. - (void)audioSessionRouteChange:(NSNotification *)notification
  552. {
  553. NSArray *outputs = [[AVAudioSession sharedInstance] currentRoute].outputs;
  554. NSString *portName = [[outputs objectAtIndex:0] portName];
  555. if (![portName isEqualToString:@"Headphones"] && [_mediaPlayer isPlaying])
  556. [_listPlayer pause];
  557. }
  558. #pragma mark - Managing the media item
  559. - (void)setFileFromMediaLibrary:(MLFile *)fileFromMediaLibrary
  560. {
  561. [self stopPlayback];
  562. _fileFromMediaLibrary = fileFromMediaLibrary;
  563. _playerIsSetup = NO;
  564. }
  565. - (void)setUrl:(NSURL *)url
  566. {
  567. [self stopPlayback];
  568. _url = url;
  569. _playerIsSetup = NO;
  570. }
  571. - (void)setMediaList:(VLCMediaList *)mediaList
  572. {
  573. [self stopPlayback];
  574. _mediaList = mediaList;
  575. _playerIsSetup = NO;
  576. }
  577. - (MLFile *)currentlyPlayingMediaFile {
  578. MLFile *mediaFile = self.fileFromMediaLibrary;
  579. if (mediaFile) {
  580. return mediaFile;
  581. } else if (self.mediaList) {
  582. NSArray *results = [MLFile fileForURL:_mediaPlayer.media.url];
  583. return results.firstObject;
  584. }
  585. return nil;
  586. }
  587. #pragma mark - metadata handling
  588. - (void)mediaDidFinishParsing:(VLCMedia *)aMedia
  589. {
  590. [self setNeedsMetadataUpdate];
  591. }
  592. - (void)mediaMetaDataDidChange:(VLCMedia*)aMedia
  593. {
  594. [self setNeedsMetadataUpdate];
  595. }
  596. - (void)setNeedsMetadataUpdate
  597. {
  598. if (_needsMetadataUpdate == NO) {
  599. _needsMetadataUpdate = YES;
  600. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  601. [self _updateDisplayedMetadata];
  602. });
  603. }
  604. }
  605. - (void)_updateDisplayedMetadata
  606. {
  607. _needsMetadataUpdate = NO;
  608. MLFile *item;
  609. NSNumber *trackNumber;
  610. NSString *title;
  611. NSString *artist;
  612. NSString *albumName;
  613. UIImage* artworkImage;
  614. BOOL mediaIsAudioOnly = NO;
  615. if (self.fileFromMediaLibrary)
  616. item = self.fileFromMediaLibrary;
  617. else if (self.mediaList) {
  618. NSArray *matches = [MLFile fileForURL:_mediaPlayer.media.url];
  619. item = matches.firstObject;
  620. }
  621. if (item) {
  622. if (item.isAlbumTrack) {
  623. title = item.albumTrack.title;
  624. artist = item.albumTrack.artist;
  625. albumName = item.albumTrack.album.name;
  626. } else
  627. title = item.title;
  628. /* MLKit knows better than us if this thing is audio only or not */
  629. mediaIsAudioOnly = [item isSupportedAudioFile];
  630. } else {
  631. NSDictionary * metaDict = _mediaPlayer.media.metaDictionary;
  632. if (metaDict) {
  633. title = metaDict[VLCMetaInformationNowPlaying] ? metaDict[VLCMetaInformationNowPlaying] : metaDict[VLCMetaInformationTitle];
  634. artist = metaDict[VLCMetaInformationArtist];
  635. albumName = metaDict[VLCMetaInformationAlbum];
  636. trackNumber = metaDict[VLCMetaInformationTrackNumber];
  637. }
  638. }
  639. if (!mediaIsAudioOnly) {
  640. /* either what we are playing is not a file known to MLKit or
  641. * MLKit fails to acknowledge that it is audio-only.
  642. * Either way, do a more expensive check to see if it is really audio-only */
  643. NSArray *tracks = _mediaPlayer.media.tracksInformation;
  644. NSUInteger trackCount = tracks.count;
  645. mediaIsAudioOnly = YES;
  646. for (NSUInteger x = 0 ; x < trackCount; x++) {
  647. if ([[tracks[x] objectForKey:VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  648. mediaIsAudioOnly = NO;
  649. break;
  650. }
  651. }
  652. }
  653. if (mediaIsAudioOnly) {
  654. artworkImage = [VLCThumbnailsCache thumbnailForManagedObject:item];
  655. if (artworkImage) {
  656. if (artist)
  657. title = [title stringByAppendingFormat:@" — %@", artist];
  658. if (albumName)
  659. title = [title stringByAppendingFormat:@" — %@", albumName];
  660. }
  661. if (title.length < 1)
  662. title = [[_mediaPlayer.media url] lastPathComponent];
  663. } else if (_mediaWasJustStarted) {
  664. _mediaWasJustStarted = NO;
  665. [(VLCAppDelegate *)[UIApplication sharedApplication].delegate presentMovieViewController];
  666. if (item) {
  667. if (_mediaPlayer.numberOfAudioTracks > 2) {
  668. if (item.lastAudioTrack.intValue > 0)
  669. _mediaPlayer.currentAudioTrackIndex = item.lastAudioTrack.intValue;
  670. }
  671. if (_mediaPlayer.numberOfSubtitlesTracks > 2) {
  672. if (item.lastSubtitleTrack.intValue > 0)
  673. _mediaPlayer.currentVideoSubTitleIndex = item.lastSubtitleTrack.intValue;
  674. }
  675. }
  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. _title = title;
  717. _artist = artist;
  718. _albumName = albumName;
  719. _artworkImage = artworkImage;
  720. _mediaIsAudioOnly = mediaIsAudioOnly;
  721. }
  722. - (void)recoverDisplayedMetadata
  723. {
  724. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:title:artwork:artist:album:audioOnly:)])
  725. [self.delegate displayMetadataForPlaybackController:self
  726. title:_title
  727. artwork:_artworkImage
  728. artist:_artist
  729. album:_albumName
  730. audioOnly:_mediaIsAudioOnly];
  731. }
  732. - (void)recoverPlaybackState
  733. {
  734. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  735. [self.delegate mediaPlayerStateChanged:_mediaPlayer.state
  736. isPlaying:self.isPlaying
  737. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  738. currentMediaHasChapters:self.currentMediaHasChapters
  739. forPlaybackController:self];
  740. }
  741. #pragma mark - remote events
  742. static inline NSArray * RemoteCommandCenterCommandsToHandle(MPRemoteCommandCenter *cc)
  743. {
  744. /* commmented out other available commands which we don't support now but may
  745. * support at some point in the future */
  746. return @[cc.pauseCommand, cc.playCommand, cc.stopCommand, cc.togglePlayPauseCommand,
  747. cc.nextTrackCommand, cc.previousTrackCommand,
  748. cc.skipForwardCommand, cc.skipBackwardCommand,
  749. // cc.seekForwardCommand, cc.seekBackwardCommand,
  750. // cc.ratingCommand,
  751. cc.changePlaybackRateCommand,
  752. // cc.likeCommand,cc.dislikeCommand,cc.bookmarkCommand,
  753. ];
  754. }
  755. - (void)subscribeRemoteCommands
  756. {
  757. /* pre iOS 7.1 */
  758. if (![MPRemoteCommandCenter class]) {
  759. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  760. return;
  761. }
  762. /* for iOS 7.1 and above: */
  763. MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
  764. /*
  765. * since the control center and lockscreen shows only either skipForward/Backward
  766. * or next/previousTrack buttons but prefers skip buttons,
  767. * we only enable skip buttons if we have a no medialist
  768. */
  769. BOOL enableSkip = [VLCPlaybackController sharedInstance].mediaList == nil;
  770. commandCenter.skipForwardCommand.enabled = enableSkip;
  771. commandCenter.skipBackwardCommand.enabled = enableSkip;
  772. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  773. NSNumber *forwardSkip = [defaults valueForKey:kVLCSettingPlaybackForwardSkipLength];
  774. commandCenter.skipForwardCommand.preferredIntervals = @[forwardSkip];
  775. NSNumber *backwardSkip = [defaults valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  776. commandCenter.skipBackwardCommand.preferredIntervals = @[backwardSkip];
  777. NSArray *supportedPlaybackRates = @[@(0.5),@(0.75),@(1.0),@(1.25),@(1.5),@(1.75),@(2.0)];
  778. commandCenter.changePlaybackRateCommand.supportedPlaybackRates = supportedPlaybackRates;
  779. NSArray *commandsToSubscribe = RemoteCommandCenterCommandsToHandle(commandCenter);
  780. for (MPRemoteCommand *command in commandsToSubscribe) {
  781. [command addTarget:self action:@selector(remoteCommandEvent:)];
  782. }
  783. }
  784. - (void)unsubscribeFromRemoteCommand
  785. {
  786. /* pre iOS 7.1 */
  787. if (![MPRemoteCommandCenter class]) {
  788. [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
  789. return;
  790. }
  791. /* for iOS 7.1 and above: */
  792. MPRemoteCommandCenter *cc = [MPRemoteCommandCenter sharedCommandCenter];
  793. NSArray *commmandsToRemoveFrom = RemoteCommandCenterCommandsToHandle(cc);
  794. for (MPRemoteCommand *command in commmandsToRemoveFrom) {
  795. [command removeTarget:self];
  796. }
  797. }
  798. - (MPRemoteCommandHandlerStatus )remoteCommandEvent:(MPRemoteCommandEvent *)event
  799. {
  800. MPRemoteCommandCenter *cc = [MPRemoteCommandCenter sharedCommandCenter];
  801. MPRemoteCommandHandlerStatus result = MPRemoteCommandHandlerStatusSuccess;
  802. if (event.command == cc.pauseCommand) {
  803. [_listPlayer pause];
  804. } else if (event.command == cc.playCommand) {
  805. [_listPlayer play];
  806. } else if (event.command == cc.stopCommand) {
  807. [_listPlayer stop];
  808. } else if (event.command == cc.togglePlayPauseCommand) {
  809. [self playPause];
  810. } else if (event.command == cc.nextTrackCommand) {
  811. result = [_listPlayer next] ? MPRemoteCommandHandlerStatusSuccess : MPRemoteCommandHandlerStatusNoSuchContent;
  812. } else if (event.command == cc.previousTrackCommand) {
  813. result = [_listPlayer previous] ? MPRemoteCommandHandlerStatusSuccess : MPRemoteCommandHandlerStatusNoSuchContent;
  814. } else if (event.command == cc.skipForwardCommand) {
  815. if ([event isKindOfClass:[MPSkipIntervalCommandEvent class]]) {
  816. MPSkipIntervalCommandEvent *skipEvent = (MPSkipIntervalCommandEvent *)event;
  817. [_mediaPlayer jumpForward:skipEvent.interval];
  818. } else {
  819. result = MPRemoteCommandHandlerStatusCommandFailed;
  820. }
  821. } else if (event.command == cc.skipBackwardCommand) {
  822. if ([event isKindOfClass:[MPSkipIntervalCommandEvent class]]) {
  823. MPSkipIntervalCommandEvent *skipEvent = (MPSkipIntervalCommandEvent *)event;
  824. [_mediaPlayer jumpBackward:skipEvent.interval];
  825. } else {
  826. result = MPRemoteCommandHandlerStatusCommandFailed;
  827. }
  828. } else if (event.command == cc.changePlaybackRateCommand) {
  829. if ([event isKindOfClass:[MPChangePlaybackRateCommandEvent class]]) {
  830. MPChangePlaybackRateCommandEvent *rateEvent = (MPChangePlaybackRateCommandEvent *)event;
  831. [_mediaPlayer setRate:rateEvent.playbackRate];
  832. } else {
  833. result = MPRemoteCommandHandlerStatusCommandFailed;
  834. }
  835. /* stubs for when we want to support the other available commands */
  836. // } else if (event.command == cc.seekForwardCommand) {
  837. // } else if (event.command == cc.seekBackwardCommand) {
  838. // } else if (event.command == cc.ratingCommand) {
  839. // } else if (event.command == cc.likeCommand) {
  840. // } else if (event.command == cc.dislikeCommand) {
  841. // } else if (event.command == cc.bookmarkCommand) {
  842. } else {
  843. APLog(@"%s Unsupported remote control event: %@",__PRETTY_FUNCTION__,event);
  844. result = MPRemoteCommandHandlerStatusCommandFailed;
  845. }
  846. if (result == MPRemoteCommandHandlerStatusCommandFailed)
  847. APLog(@"%s Wasn't able to handle remote control event: %@",__PRETTY_FUNCTION__,event);
  848. return result;
  849. }
  850. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  851. {
  852. switch (event.subtype) {
  853. case UIEventSubtypeRemoteControlPlay:
  854. [_listPlayer play];
  855. break;
  856. case UIEventSubtypeRemoteControlPause:
  857. [_listPlayer pause];
  858. break;
  859. case UIEventSubtypeRemoteControlTogglePlayPause:
  860. [self playPause];
  861. break;
  862. case UIEventSubtypeRemoteControlNextTrack:
  863. [self forward];
  864. break;
  865. case UIEventSubtypeRemoteControlPreviousTrack:
  866. [self backward];
  867. break;
  868. case UIEventSubtypeRemoteControlStop:
  869. [self stopPlayback];
  870. break;
  871. default:
  872. break;
  873. }
  874. }
  875. #pragma mark - background interaction
  876. - (void)applicationWillResignActive:(NSNotification *)aNotification
  877. {
  878. [self _savePlaybackState];
  879. _preBackgroundWrapperView = _videoOutputViewWrapper;
  880. [self setVideoOutputView:nil];
  881. if (_mediaPlayer.audioTrackIndexes.count > 0)
  882. _mediaPlayer.currentVideoTrackIndex = -1;
  883. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  884. if ([_mediaPlayer isPlaying]) {
  885. [_mediaPlayer pause];
  886. _shouldResumePlaying = YES;
  887. }
  888. }
  889. }
  890. - (void)applicationDidEnterBackground:(NSNotification *)notification
  891. {
  892. _shouldResumePlaying = NO;
  893. }
  894. - (void)applicationDidBecomeActive:(NSNotification *)notification
  895. {
  896. if (_preBackgroundWrapperView) {
  897. [self setVideoOutputView:_preBackgroundWrapperView];
  898. _preBackgroundWrapperView = nil;
  899. }
  900. if (_mediaPlayer.numberOfVideoTracks > 0) {
  901. /* re-enable video decoding and reset position once done */
  902. float position = _mediaPlayer.position;
  903. _mediaPlayer.currentVideoTrackIndex = 1;
  904. _mediaPlayer.position = position;
  905. }
  906. if (_shouldResumePlaying) {
  907. _shouldResumePlaying = NO;
  908. [_listPlayer play];
  909. }
  910. }
  911. #pragma mark - helpers
  912. - (NSString *)_resolveFontName
  913. {
  914. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  915. BOOL bold = [[defaults objectForKey:kVLCSettingSubtitlesBoldFont] boolValue];
  916. NSString *font = [defaults objectForKey:kVLCSettingSubtitlesFont];
  917. NSDictionary *fontMap = @{
  918. @"AmericanTypewriter": @"AmericanTypewriter-Bold",
  919. @"ArialMT": @"Arial-BoldMT",
  920. @"ArialHebrew": @"ArialHebrew-Bold",
  921. @"ChalkboardSE-Regular": @"ChalkboardSE-Bold",
  922. @"CourierNewPSMT": @"CourierNewPS-BoldMT",
  923. @"Georgia": @"Georgia-Bold",
  924. @"GillSans": @"GillSans-Bold",
  925. @"GujaratiSangamMN": @"GujaratiSangamMN-Bold",
  926. @"STHeitiSC-Light": @"STHeitiSC-Medium",
  927. @"STHeitiTC-Light": @"STHeitiTC-Medium",
  928. @"HelveticaNeue": @"HelveticaNeue-Bold",
  929. @"HiraKakuProN-W3": @"HiraKakuProN-W6",
  930. @"HiraMinProN-W3": @"HiraMinProN-W6",
  931. @"HoeflerText-Regular": @"HoeflerText-Black",
  932. @"Kailasa": @"Kailasa-Bold",
  933. @"KannadaSangamMN": @"KannadaSangamMN-Bold",
  934. @"MalayalamSangamMN": @"MalayalamSangamMN-Bold",
  935. @"OriyaSangamMN": @"OriyaSangamMN-Bold",
  936. @"SinhalaSangamMN": @"SinhalaSangamMN-Bold",
  937. @"SnellRoundhand": @"SnellRoundhand-Bold",
  938. @"TamilSangamMN": @"TamilSangamMN-Bold",
  939. @"TeluguSangamMN": @"TeluguSangamMN-Bold",
  940. @"TimesNewRomanPSMT": @"TimesNewRomanPS-BoldMT",
  941. @"Zapfino": @"Zapfino"
  942. };
  943. if (!bold) {
  944. return font;
  945. } else {
  946. return fontMap[font];
  947. }
  948. }
  949. @end