VLCPlaybackController.m 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  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. _currentPlaybackRate = f_rate;
  369. return f_rate;
  370. }
  371. - (void)setPlaybackRate:(float)playbackRate
  372. {
  373. if (_currentPlaybackRate != playbackRate)
  374. [_mediaPlayer setRate:playbackRate];
  375. _currentPlaybackRate = playbackRate;
  376. }
  377. - (void)setAudioDelay:(float)audioDelay
  378. {
  379. _mediaPlayer.currentAudioPlaybackDelay = 1000000.*audioDelay;
  380. }
  381. - (float)audioDelay
  382. {
  383. return _mediaPlayer.currentAudioPlaybackDelay/1000000.;
  384. }
  385. -(void)setSubtitleDelay:(float)subtitleDeleay
  386. {
  387. _mediaPlayer.currentVideoSubTitleDelay = 1000000.*subtitleDeleay;
  388. }
  389. - (float)subtitleDelay
  390. {
  391. return _mediaPlayer.currentVideoSubTitleDelay/1000000.;
  392. }
  393. - (void)mediaPlayerStateChanged:(NSNotification *)aNotification
  394. {
  395. VLCMediaPlayerState currentState = _mediaPlayer.state;
  396. if (currentState == VLCMediaPlayerStateBuffering) {
  397. /* attach delegate */
  398. _mediaPlayer.media.delegate = self;
  399. /* on-the-fly values through hidden API */
  400. [_mediaPlayer performSelector:@selector(setTextRendererFont:) withObject:[self _resolveFontName]];
  401. [_mediaPlayer performSelector:@selector(setTextRendererFontSize:) withObject:[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingSubtitlesFontSize]];
  402. [_mediaPlayer performSelector:@selector(setTextRendererFontColor:) withObject:[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingSubtitlesFontColor]];
  403. } else if (currentState == VLCMediaPlayerStateError) {
  404. _playbackFailed = YES;
  405. if ([self.delegate respondsToSelector:@selector(presentingViewControllerShouldBeClosedAfterADelay:)])
  406. [self.delegate presentingViewControllerShouldBeClosedAfterADelay:self];
  407. [self stopPlayback];
  408. } else if ((currentState == VLCMediaPlayerStateEnded || currentState == VLCMediaPlayerStateStopped) && _listPlayer.repeatMode == VLCDoNotRepeat) {
  409. if ([_listPlayer.mediaList indexOfMedia:_mediaPlayer.media] == _listPlayer.mediaList.count - 1) {
  410. if ([self.delegate respondsToSelector:@selector(presentingViewControllerShouldBeClosed:)])
  411. [self.delegate presentingViewControllerShouldBeClosed:self];
  412. [self stopPlayback];
  413. return;
  414. }
  415. } else {
  416. /* disable video decoding if we have no place to show */
  417. if (_mediaPlayer.numberOfAudioTracks > 0) {
  418. if (_videoOutputViewWrapper == nil)
  419. _mediaPlayer.currentVideoTrackIndex = -1;
  420. }
  421. }
  422. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  423. [self.delegate mediaPlayerStateChanged:currentState
  424. isPlaying:_mediaPlayer.isPlaying
  425. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  426. currentMediaHasChapters:self.currentMediaHasChapters
  427. forPlaybackController:self];
  428. [self setNeedsMetadataUpdate];
  429. }
  430. #pragma mark - playback controls
  431. - (void)playPause
  432. {
  433. if ([_mediaPlayer isPlaying])
  434. [_listPlayer pause];
  435. else
  436. [_listPlayer play];
  437. }
  438. - (void)forward
  439. {
  440. if (_mediaList) {
  441. [_listPlayer next];
  442. } else {
  443. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackForwardSkipLength];
  444. [_mediaPlayer jumpForward:skipLength.intValue];
  445. }
  446. }
  447. - (void)backward
  448. {
  449. if (_mediaList) {
  450. [_listPlayer previous];
  451. }
  452. else {
  453. NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  454. [_mediaPlayer jumpBackward:skipLength.intValue];
  455. }
  456. }
  457. - (void)switchAspectRatio
  458. {
  459. NSUInteger count = [_aspectRatios count];
  460. if (_currentAspectRatioMask + 1 > count - 1) {
  461. _mediaPlayer.videoAspectRatio = NULL;
  462. _mediaPlayer.videoCropGeometry = NULL;
  463. _currentAspectRatioMask = 0;
  464. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  465. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), NSLocalizedString(@"DEFAULT", nil)] forPlaybackController:self];
  466. } else {
  467. _currentAspectRatioMask++;
  468. if ([_aspectRatios[_currentAspectRatioMask] isEqualToString:@"FILL_TO_SCREEN"]) {
  469. UIScreen *screen;
  470. if (![[UIDevice currentDevice] hasExternalDisplay])
  471. screen = [UIScreen mainScreen];
  472. else
  473. screen = [UIScreen screens][1];
  474. float f_ar = screen.bounds.size.width / screen.bounds.size.height;
  475. if (f_ar == (float)(640./1136.)) // iPhone 5 aka 16:9.01
  476. _mediaPlayer.videoCropGeometry = "16:9";
  477. else if (f_ar == (float)(2./3.)) // all other iPhones
  478. _mediaPlayer.videoCropGeometry = "16:10"; // libvlc doesn't support 2:3 crop
  479. else if (f_ar == .75) // all iPads
  480. _mediaPlayer.videoCropGeometry = "4:3";
  481. else if (f_ar == .5625) // AirPlay
  482. _mediaPlayer.videoCropGeometry = "16:9";
  483. else
  484. APLog(@"unknown screen format %f, can't crop", f_ar);
  485. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  486. [self.delegate showStatusMessage:NSLocalizedString(@"FILL_TO_SCREEN", nil) forPlaybackController:self];
  487. return;
  488. }
  489. _mediaPlayer.videoCropGeometry = NULL;
  490. _mediaPlayer.videoAspectRatio = (char *)[_aspectRatios[_currentAspectRatioMask] UTF8String];
  491. if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)])
  492. [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), _aspectRatios[_currentAspectRatioMask]] forPlaybackController:self];
  493. }
  494. }
  495. - (void)setVideoOutputView:(UIView *)videoOutputView
  496. {
  497. if (videoOutputView) {
  498. if ([_actualVideoOutputView superview] != nil)
  499. [_actualVideoOutputView removeFromSuperview];
  500. _actualVideoOutputView.frame = (CGRect){CGPointZero, videoOutputView.frame.size};
  501. [_actualVideoOutputView layoutSubviews];
  502. [_actualVideoOutputView updateConstraints];
  503. if (_mediaPlayer.currentVideoTrackIndex == -1)
  504. _mediaPlayer.currentVideoTrackIndex = 0;
  505. [videoOutputView addSubview:_actualVideoOutputView];
  506. } else
  507. [_actualVideoOutputView removeFromSuperview];
  508. _videoOutputViewWrapper = videoOutputView;
  509. }
  510. - (UIView *)videoOutputView
  511. {
  512. return _videoOutputViewWrapper;
  513. }
  514. #pragma mark - equalizer
  515. - (void)setAmplification:(CGFloat)amplification forBand:(unsigned int)index
  516. {
  517. if (!_mediaPlayer.equalizerEnabled)
  518. [_mediaPlayer setEqualizerEnabled:YES];
  519. [_mediaPlayer setAmplification:amplification forBand:index];
  520. // For some reason we have to apply again preamp to apply change
  521. [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
  522. }
  523. - (CGFloat)amplificationOfBand:(unsigned int)index
  524. {
  525. return [_mediaPlayer amplificationOfBand:index];
  526. }
  527. - (NSArray *)equalizerProfiles
  528. {
  529. return _mediaPlayer.equalizerProfiles;
  530. }
  531. - (void)resetEqualizerFromProfile:(unsigned int)profile
  532. {
  533. [[NSUserDefaults standardUserDefaults] setObject:@(profile) forKey:kVLCSettingEqualizerProfile];
  534. [_mediaPlayer resetEqualizerFromProfile:profile];
  535. }
  536. - (void)setPreAmplification:(CGFloat)preAmplification
  537. {
  538. if (!_mediaPlayer.equalizerEnabled)
  539. [_mediaPlayer setEqualizerEnabled:YES];
  540. [_mediaPlayer setPreAmplification:preAmplification];
  541. }
  542. - (CGFloat)preAmplification
  543. {
  544. return [_mediaPlayer preAmplification];
  545. }
  546. #pragma mark - AVSession delegate
  547. - (void)beginInterruption
  548. {
  549. if ([_mediaPlayer isPlaying]) {
  550. [_mediaPlayer pause];
  551. _shouldResumePlaying = YES;
  552. }
  553. }
  554. - (void)endInterruption
  555. {
  556. if (_shouldResumePlaying) {
  557. [_mediaPlayer play];
  558. _shouldResumePlaying = NO;
  559. }
  560. }
  561. - (void)audioSessionRouteChange:(NSNotification *)notification
  562. {
  563. NSArray *outputs = [[AVAudioSession sharedInstance] currentRoute].outputs;
  564. NSString *portName = [[outputs objectAtIndex:0] portName];
  565. if (![portName isEqualToString:@"Headphones"] && [_mediaPlayer isPlaying])
  566. [_listPlayer pause];
  567. }
  568. #pragma mark - Managing the media item
  569. - (void)setFileFromMediaLibrary:(MLFile *)fileFromMediaLibrary
  570. {
  571. [self stopPlayback];
  572. _fileFromMediaLibrary = fileFromMediaLibrary;
  573. _playerIsSetup = NO;
  574. }
  575. - (void)setUrl:(NSURL *)url
  576. {
  577. [self stopPlayback];
  578. _url = url;
  579. _playerIsSetup = NO;
  580. }
  581. - (void)setMediaList:(VLCMediaList *)mediaList
  582. {
  583. [self stopPlayback];
  584. _mediaList = mediaList;
  585. _playerIsSetup = NO;
  586. }
  587. - (MLFile *)currentlyPlayingMediaFile {
  588. MLFile *mediaFile = self.fileFromMediaLibrary;
  589. if (mediaFile) {
  590. return mediaFile;
  591. } else if (self.mediaList) {
  592. NSArray *results = [MLFile fileForURL:_mediaPlayer.media.url];
  593. return results.firstObject;
  594. }
  595. return nil;
  596. }
  597. #pragma mark - metadata handling
  598. - (void)mediaDidFinishParsing:(VLCMedia *)aMedia
  599. {
  600. [self setNeedsMetadataUpdate];
  601. }
  602. - (void)mediaMetaDataDidChange:(VLCMedia*)aMedia
  603. {
  604. [self setNeedsMetadataUpdate];
  605. }
  606. - (void)setNeedsMetadataUpdate
  607. {
  608. if (_needsMetadataUpdate == NO) {
  609. _needsMetadataUpdate = YES;
  610. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  611. [self _updateDisplayedMetadata];
  612. });
  613. }
  614. }
  615. - (void)_updateDisplayedMetadata
  616. {
  617. _needsMetadataUpdate = NO;
  618. MLFile *item;
  619. NSNumber *trackNumber;
  620. NSString *title;
  621. NSString *artist;
  622. NSString *albumName;
  623. UIImage* artworkImage;
  624. BOOL mediaIsAudioOnly = NO;
  625. if (self.fileFromMediaLibrary)
  626. item = self.fileFromMediaLibrary;
  627. else if (self.mediaList) {
  628. NSArray *matches = [MLFile fileForURL:_mediaPlayer.media.url];
  629. item = matches.firstObject;
  630. }
  631. if (item) {
  632. if (item.isAlbumTrack) {
  633. title = item.albumTrack.title;
  634. artist = item.albumTrack.artist;
  635. albumName = item.albumTrack.album.name;
  636. } else
  637. title = item.title;
  638. /* MLKit knows better than us if this thing is audio only or not */
  639. mediaIsAudioOnly = [item isSupportedAudioFile];
  640. } else {
  641. NSDictionary * metaDict = _mediaPlayer.media.metaDictionary;
  642. if (metaDict) {
  643. title = metaDict[VLCMetaInformationNowPlaying] ? metaDict[VLCMetaInformationNowPlaying] : metaDict[VLCMetaInformationTitle];
  644. artist = metaDict[VLCMetaInformationArtist];
  645. albumName = metaDict[VLCMetaInformationAlbum];
  646. trackNumber = metaDict[VLCMetaInformationTrackNumber];
  647. }
  648. }
  649. if (!mediaIsAudioOnly) {
  650. /* either what we are playing is not a file known to MLKit or
  651. * MLKit fails to acknowledge that it is audio-only.
  652. * Either way, do a more expensive check to see if it is really audio-only */
  653. NSArray *tracks = _mediaPlayer.media.tracksInformation;
  654. NSUInteger trackCount = tracks.count;
  655. mediaIsAudioOnly = YES;
  656. for (NSUInteger x = 0 ; x < trackCount; x++) {
  657. if ([[tracks[x] objectForKey:VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  658. mediaIsAudioOnly = NO;
  659. break;
  660. }
  661. }
  662. }
  663. if (mediaIsAudioOnly) {
  664. artworkImage = [VLCThumbnailsCache thumbnailForManagedObject:item];
  665. if (artworkImage) {
  666. if (artist)
  667. title = [title stringByAppendingFormat:@" — %@", artist];
  668. if (albumName)
  669. title = [title stringByAppendingFormat:@" — %@", albumName];
  670. }
  671. if (title.length < 1)
  672. title = [[_mediaPlayer.media url] lastPathComponent];
  673. } else if (_mediaWasJustStarted) {
  674. _mediaWasJustStarted = NO;
  675. [(VLCAppDelegate *)[UIApplication sharedApplication].delegate presentMovieViewController];
  676. if (item) {
  677. if (_mediaPlayer.numberOfAudioTracks > 2) {
  678. if (item.lastAudioTrack.intValue > 0)
  679. _mediaPlayer.currentAudioTrackIndex = item.lastAudioTrack.intValue;
  680. }
  681. if (_mediaPlayer.numberOfSubtitlesTracks > 2) {
  682. if (item.lastSubtitleTrack.intValue > 0)
  683. _mediaPlayer.currentVideoSubTitleIndex = item.lastSubtitleTrack.intValue;
  684. }
  685. }
  686. }
  687. /* populate delegate with metadata info */
  688. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:title:artwork:artist:album:audioOnly:)])
  689. [self.delegate displayMetadataForPlaybackController:self
  690. title:title
  691. artwork:artworkImage
  692. artist:artist
  693. album:albumName
  694. audioOnly:mediaIsAudioOnly];
  695. /* populate now playing info center with metadata information */
  696. NSMutableDictionary *currentlyPlayingTrackInfo = [NSMutableDictionary dictionary];
  697. currentlyPlayingTrackInfo[MPMediaItemPropertyPlaybackDuration] = @(_mediaPlayer.media.length.intValue / 1000.);
  698. currentlyPlayingTrackInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = @(_mediaPlayer.time.intValue / 1000.);
  699. currentlyPlayingTrackInfo[MPNowPlayingInfoPropertyPlaybackRate] = @(_mediaPlayer.isPlaying ? _mediaPlayer.rate : 0.0);
  700. /* don't leak sensitive information to the OS, if passcode lock is enabled */
  701. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingPasscodeOnKey] boolValue]) {
  702. if (title)
  703. currentlyPlayingTrackInfo[MPMediaItemPropertyTitle] = title;
  704. if (artist.length > 0)
  705. currentlyPlayingTrackInfo[MPMediaItemPropertyArtist] = artist;
  706. if (albumName.length > 0)
  707. currentlyPlayingTrackInfo[MPMediaItemPropertyAlbumTitle] = albumName;
  708. if ([trackNumber intValue] > 0)
  709. currentlyPlayingTrackInfo[MPMediaItemPropertyAlbumTrackNumber] = trackNumber;
  710. /* FIXME: UGLY HACK
  711. * iOS 8.2 and 8.3 include an issue which will lead to a termination of the client app if we set artwork
  712. * when the playback initialized through the watch extension
  713. * radar://pending */
  714. if ([WKInterfaceDevice class] != nil) {
  715. if ([WKInterfaceDevice currentDevice] != nil)
  716. goto setstuff;
  717. }
  718. if (artworkImage) {
  719. MPMediaItemArtwork *mpartwork = [[MPMediaItemArtwork alloc] initWithImage:artworkImage];
  720. currentlyPlayingTrackInfo[MPMediaItemPropertyArtwork] = mpartwork;
  721. }
  722. }
  723. setstuff:
  724. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = currentlyPlayingTrackInfo;
  725. [[NSNotificationCenter defaultCenter] postNotificationName:kVLCNotificationNowPlayingInfoUpdate object:self];
  726. _title = title;
  727. _artist = artist;
  728. _albumName = albumName;
  729. _artworkImage = artworkImage;
  730. _mediaIsAudioOnly = mediaIsAudioOnly;
  731. }
  732. - (void)recoverDisplayedMetadata
  733. {
  734. if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:title:artwork:artist:album:audioOnly:)])
  735. [self.delegate displayMetadataForPlaybackController:self
  736. title:_title
  737. artwork:_artworkImage
  738. artist:_artist
  739. album:_albumName
  740. audioOnly:_mediaIsAudioOnly];
  741. }
  742. - (void)recoverPlaybackState
  743. {
  744. if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
  745. [self.delegate mediaPlayerStateChanged:_mediaPlayer.state
  746. isPlaying:self.isPlaying
  747. currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
  748. currentMediaHasChapters:self.currentMediaHasChapters
  749. forPlaybackController:self];
  750. }
  751. #pragma mark - remote events
  752. static inline NSArray * RemoteCommandCenterCommandsToHandle(MPRemoteCommandCenter *cc)
  753. {
  754. /* commmented out other available commands which we don't support now but may
  755. * support at some point in the future */
  756. return @[cc.pauseCommand, cc.playCommand, cc.stopCommand, cc.togglePlayPauseCommand,
  757. cc.nextTrackCommand, cc.previousTrackCommand,
  758. cc.skipForwardCommand, cc.skipBackwardCommand,
  759. // cc.seekForwardCommand, cc.seekBackwardCommand,
  760. // cc.ratingCommand,
  761. cc.changePlaybackRateCommand,
  762. // cc.likeCommand,cc.dislikeCommand,cc.bookmarkCommand,
  763. ];
  764. }
  765. - (void)subscribeRemoteCommands
  766. {
  767. /* pre iOS 7.1 */
  768. if (![MPRemoteCommandCenter class]) {
  769. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  770. return;
  771. }
  772. /* for iOS 7.1 and above: */
  773. MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
  774. /*
  775. * since the control center and lockscreen shows only either skipForward/Backward
  776. * or next/previousTrack buttons but prefers skip buttons,
  777. * we only enable skip buttons if we have a no medialist
  778. */
  779. BOOL enableSkip = [VLCPlaybackController sharedInstance].mediaList == nil;
  780. commandCenter.skipForwardCommand.enabled = enableSkip;
  781. commandCenter.skipBackwardCommand.enabled = enableSkip;
  782. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  783. NSNumber *forwardSkip = [defaults valueForKey:kVLCSettingPlaybackForwardSkipLength];
  784. commandCenter.skipForwardCommand.preferredIntervals = @[forwardSkip];
  785. NSNumber *backwardSkip = [defaults valueForKey:kVLCSettingPlaybackBackwardSkipLength];
  786. commandCenter.skipBackwardCommand.preferredIntervals = @[backwardSkip];
  787. NSArray *supportedPlaybackRates = @[@(0.5),@(0.75),@(1.0),@(1.25),@(1.5),@(1.75),@(2.0)];
  788. commandCenter.changePlaybackRateCommand.supportedPlaybackRates = supportedPlaybackRates;
  789. NSArray *commandsToSubscribe = RemoteCommandCenterCommandsToHandle(commandCenter);
  790. for (MPRemoteCommand *command in commandsToSubscribe) {
  791. [command addTarget:self action:@selector(remoteCommandEvent:)];
  792. }
  793. }
  794. - (void)unsubscribeFromRemoteCommand
  795. {
  796. /* pre iOS 7.1 */
  797. if (![MPRemoteCommandCenter class]) {
  798. [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
  799. return;
  800. }
  801. /* for iOS 7.1 and above: */
  802. MPRemoteCommandCenter *cc = [MPRemoteCommandCenter sharedCommandCenter];
  803. NSArray *commmandsToRemoveFrom = RemoteCommandCenterCommandsToHandle(cc);
  804. for (MPRemoteCommand *command in commmandsToRemoveFrom) {
  805. [command removeTarget:self];
  806. }
  807. }
  808. - (MPRemoteCommandHandlerStatus )remoteCommandEvent:(MPRemoteCommandEvent *)event
  809. {
  810. MPRemoteCommandCenter *cc = [MPRemoteCommandCenter sharedCommandCenter];
  811. MPRemoteCommandHandlerStatus result = MPRemoteCommandHandlerStatusSuccess;
  812. if (event.command == cc.pauseCommand) {
  813. [_listPlayer pause];
  814. } else if (event.command == cc.playCommand) {
  815. [_listPlayer play];
  816. } else if (event.command == cc.stopCommand) {
  817. [_listPlayer stop];
  818. } else if (event.command == cc.togglePlayPauseCommand) {
  819. [self playPause];
  820. } else if (event.command == cc.nextTrackCommand) {
  821. result = [_listPlayer next] ? MPRemoteCommandHandlerStatusSuccess : MPRemoteCommandHandlerStatusNoSuchContent;
  822. } else if (event.command == cc.previousTrackCommand) {
  823. result = [_listPlayer previous] ? MPRemoteCommandHandlerStatusSuccess : MPRemoteCommandHandlerStatusNoSuchContent;
  824. } else if (event.command == cc.skipForwardCommand) {
  825. if ([event isKindOfClass:[MPSkipIntervalCommandEvent class]]) {
  826. MPSkipIntervalCommandEvent *skipEvent = (MPSkipIntervalCommandEvent *)event;
  827. [_mediaPlayer jumpForward:skipEvent.interval];
  828. } else {
  829. result = MPRemoteCommandHandlerStatusCommandFailed;
  830. }
  831. } else if (event.command == cc.skipBackwardCommand) {
  832. if ([event isKindOfClass:[MPSkipIntervalCommandEvent class]]) {
  833. MPSkipIntervalCommandEvent *skipEvent = (MPSkipIntervalCommandEvent *)event;
  834. [_mediaPlayer jumpBackward:skipEvent.interval];
  835. } else {
  836. result = MPRemoteCommandHandlerStatusCommandFailed;
  837. }
  838. } else if (event.command == cc.changePlaybackRateCommand) {
  839. if ([event isKindOfClass:[MPChangePlaybackRateCommandEvent class]]) {
  840. MPChangePlaybackRateCommandEvent *rateEvent = (MPChangePlaybackRateCommandEvent *)event;
  841. [_mediaPlayer setRate:rateEvent.playbackRate];
  842. } else {
  843. result = MPRemoteCommandHandlerStatusCommandFailed;
  844. }
  845. /* stubs for when we want to support the other available commands */
  846. // } else if (event.command == cc.seekForwardCommand) {
  847. // } else if (event.command == cc.seekBackwardCommand) {
  848. // } else if (event.command == cc.ratingCommand) {
  849. // } else if (event.command == cc.likeCommand) {
  850. // } else if (event.command == cc.dislikeCommand) {
  851. // } else if (event.command == cc.bookmarkCommand) {
  852. } else {
  853. APLog(@"%s Unsupported remote control event: %@",__PRETTY_FUNCTION__,event);
  854. result = MPRemoteCommandHandlerStatusCommandFailed;
  855. }
  856. if (result == MPRemoteCommandHandlerStatusCommandFailed)
  857. APLog(@"%s Wasn't able to handle remote control event: %@",__PRETTY_FUNCTION__,event);
  858. return result;
  859. }
  860. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  861. {
  862. switch (event.subtype) {
  863. case UIEventSubtypeRemoteControlPlay:
  864. [_listPlayer play];
  865. break;
  866. case UIEventSubtypeRemoteControlPause:
  867. [_listPlayer pause];
  868. break;
  869. case UIEventSubtypeRemoteControlTogglePlayPause:
  870. [self playPause];
  871. break;
  872. case UIEventSubtypeRemoteControlNextTrack:
  873. [self forward];
  874. break;
  875. case UIEventSubtypeRemoteControlPreviousTrack:
  876. [self backward];
  877. break;
  878. case UIEventSubtypeRemoteControlStop:
  879. [self stopPlayback];
  880. break;
  881. default:
  882. break;
  883. }
  884. }
  885. #pragma mark - background interaction
  886. - (void)applicationWillResignActive:(NSNotification *)aNotification
  887. {
  888. [self _savePlaybackState];
  889. _preBackgroundWrapperView = _videoOutputViewWrapper;
  890. [self setVideoOutputView:nil];
  891. if (_mediaPlayer.audioTrackIndexes.count > 0)
  892. _mediaPlayer.currentVideoTrackIndex = -1;
  893. if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
  894. if ([_mediaPlayer isPlaying]) {
  895. [_mediaPlayer pause];
  896. _shouldResumePlaying = YES;
  897. }
  898. }
  899. }
  900. - (void)applicationDidEnterBackground:(NSNotification *)notification
  901. {
  902. _shouldResumePlaying = NO;
  903. }
  904. - (void)applicationDidBecomeActive:(NSNotification *)notification
  905. {
  906. if (_preBackgroundWrapperView) {
  907. [self setVideoOutputView:_preBackgroundWrapperView];
  908. _preBackgroundWrapperView = nil;
  909. }
  910. if (_mediaPlayer.numberOfVideoTracks > 0) {
  911. /* re-enable video decoding and reset position once done */
  912. float position = _mediaPlayer.position;
  913. _mediaPlayer.currentVideoTrackIndex = 1;
  914. _mediaPlayer.position = position;
  915. }
  916. if (_shouldResumePlaying) {
  917. _shouldResumePlaying = NO;
  918. [_listPlayer play];
  919. }
  920. }
  921. #pragma mark - helpers
  922. - (NSString *)_resolveFontName
  923. {
  924. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  925. BOOL bold = [[defaults objectForKey:kVLCSettingSubtitlesBoldFont] boolValue];
  926. NSString *font = [defaults objectForKey:kVLCSettingSubtitlesFont];
  927. NSDictionary *fontMap = @{
  928. @"AmericanTypewriter": @"AmericanTypewriter-Bold",
  929. @"ArialMT": @"Arial-BoldMT",
  930. @"ArialHebrew": @"ArialHebrew-Bold",
  931. @"ChalkboardSE-Regular": @"ChalkboardSE-Bold",
  932. @"CourierNewPSMT": @"CourierNewPS-BoldMT",
  933. @"Georgia": @"Georgia-Bold",
  934. @"GillSans": @"GillSans-Bold",
  935. @"GujaratiSangamMN": @"GujaratiSangamMN-Bold",
  936. @"STHeitiSC-Light": @"STHeitiSC-Medium",
  937. @"STHeitiTC-Light": @"STHeitiTC-Medium",
  938. @"HelveticaNeue": @"HelveticaNeue-Bold",
  939. @"HiraKakuProN-W3": @"HiraKakuProN-W6",
  940. @"HiraMinProN-W3": @"HiraMinProN-W6",
  941. @"HoeflerText-Regular": @"HoeflerText-Black",
  942. @"Kailasa": @"Kailasa-Bold",
  943. @"KannadaSangamMN": @"KannadaSangamMN-Bold",
  944. @"MalayalamSangamMN": @"MalayalamSangamMN-Bold",
  945. @"OriyaSangamMN": @"OriyaSangamMN-Bold",
  946. @"SinhalaSangamMN": @"SinhalaSangamMN-Bold",
  947. @"SnellRoundhand": @"SnellRoundhand-Bold",
  948. @"TamilSangamMN": @"TamilSangamMN-Bold",
  949. @"TeluguSangamMN": @"TeluguSangamMN-Bold",
  950. @"TimesNewRomanPSMT": @"TimesNewRomanPS-BoldMT",
  951. @"Zapfino": @"Zapfino"
  952. };
  953. if (!bold) {
  954. return font;
  955. } else {
  956. return fontMap[font];
  957. }
  958. }
  959. @end