VLCPlaybackController.m 43 KB

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