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