VLCPlaybackController.m 45 KB

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