VLCPlaybackController.m 42 KB

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