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