VLCPlaybackController.m 49.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*****************************************************************************
 * VLCPlaybackController.m
 * VLC for iOS
 *****************************************************************************
 * Copyright (c) 2013-2015 VideoLAN. All rights reserved.
 * $Id$
 *
 * Authors: Felix Paul Kühne <fkuehne # videolan.org>
 *          Carola Nitz <caro # videolan.org>
 *          Gleb Pinigin <gpinigin # gmail.com>
 *          Pierre Sagaspe <pierre.sagaspe # me.com>
 *          Tobias Conradi <videolan # tobias-conradi.de>
 *          Sylver Bruneau <sylver.bruneau # gmail dot com>
 *          Winston Weinert <winston # ml1 dot net>
 *
 * Refer to the COPYING file of the official project for license.
 *****************************************************************************/

#import "VLCPlaybackController.h"
#import <CommonCrypto/CommonDigest.h>
#import "UIDevice+VLC.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
24
#import "VLCPlayerDisplayController.h"
25
#import "VLCConstants.h"
Felix Paul Kühne's avatar
Felix Paul Kühne committed
26 27 28

#if TARGET_OS_IOS
#import "VLCKeychainCoordinator.h"
29
#import "VLCThumbnailsCache.h"
30
#import "VLCLibraryViewController.h"
Felix Paul Kühne's avatar
Felix Paul Kühne committed
31 32
#import <WatchKit/WatchKit.h>
#endif
33

34 35 36 37 38 39
NSString *const VLCPlaybackControllerPlaybackDidStart = @"VLCPlaybackControllerPlaybackDidStart";
NSString *const VLCPlaybackControllerPlaybackDidPause = @"VLCPlaybackControllerPlaybackDidPause";
NSString *const VLCPlaybackControllerPlaybackDidResume = @"VLCPlaybackControllerPlaybackDidResume";
NSString *const VLCPlaybackControllerPlaybackDidStop = @"VLCPlaybackControllerPlaybackDidStop";
NSString *const VLCPlaybackControllerPlaybackMetadataDidChange = @"VLCPlaybackControllerPlaybackMetadataDidChange";
NSString *const VLCPlaybackControllerPlaybackDidFail = @"VLCPlaybackControllerPlaybackDidFail";
40
NSString *const VLCPlaybackControllerPlaybackPositionUpdated = @"VLCPlaybackControllerPlaybackPositionUpdated";
41

42 43 44 45 46 47 48 49
typedef NS_ENUM(NSUInteger, VLCAspectRatio) {
    VLCAspectRatioDefault = 0,
    VLCAspectRatioFillToScreen,
    VLCAspectRatioFourToThree,
    VLCAspectRatioSixteenToNine,
    VLCAspectRatioSixteenToTen,
};

50 51 52 53 54
@interface VLCPlaybackController () <VLCMediaPlayerDelegate,
#if TARGET_OS_IOS
AVAudioSessionDelegate,
#endif
VLCMediaDelegate>
55 56 57 58
{
    BOOL _playerIsSetup;
    BOOL _playbackFailed;
    BOOL _shouldResumePlaying;
59
    BOOL _shouldResumePlayingAfterInteruption;
60
    NSTimer *_sleepTimer;
61

62
    NSUInteger _currentAspectRatio;
63 64 65 66

    float _currentPlaybackRate;
    UIView *_videoOutputViewWrapper;
    UIView *_actualVideoOutputView;
67
    UIView *_preBackgroundWrapperView;
68 69 70 71 72 73 74

    /* cached stuff for the VC */
    NSString *_title;
    UIImage *_artworkImage;
    NSString *_artist;
    NSString *_albumName;
    BOOL _mediaIsAudioOnly;
75 76

    BOOL _needsMetadataUpdate;
77
    BOOL _mediaWasJustStarted;
78
    BOOL _recheckForExistingThumbnail;
79
    BOOL _activeSession;
80
    BOOL _headphonesWasPlugged;
81 82

    NSLock *_playbackSessionManagementLock;
83 84

    VLCDialogProvider *_dialogProvider;
Soomin Lee's avatar
Soomin Lee committed
85 86

    NSMutableArray *_shuffleStack;
87 88 89 90 91 92 93 94 95 96 97 98 99 100
}

@end

@implementation VLCPlaybackController

#pragma mark instance management

+ (VLCPlaybackController *)sharedInstance
{
    static VLCPlaybackController *sharedInstance = nil;
    static dispatch_once_t pred;

    dispatch_once(&pred, ^{
101
        sharedInstance = [VLCPlaybackController new];
102 103 104 105 106 107 108
    });

    return sharedInstance;
}

- (void)dealloc
{
109
    _dialogProvider = nil;
110 111 112
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

Tobias's avatar
Tobias committed
113 114 115 116
- (instancetype)init
{
    self = [super init];
    if (self) {
117
        _headphonesWasPlugged = [self areHeadphonesPlugged];
Tobias's avatar
Tobias committed
118 119 120 121 122 123 124 125 126
        NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
        [defaultCenter addObserver:self selector:@selector(audioSessionRouteChange:)
                              name:AVAudioSessionRouteChangeNotification object:nil];
        [defaultCenter addObserver:self selector:@selector(applicationWillResignActive:)
                              name:UIApplicationWillResignActiveNotification object:nil];
        [defaultCenter addObserver:self selector:@selector(applicationDidBecomeActive:)
                              name:UIApplicationDidBecomeActiveNotification object:nil];
        [defaultCenter addObserver:self selector:@selector(applicationDidEnterBackground:)
                              name:UIApplicationDidEnterBackgroundNotification object:nil];
127

128 129
        _dialogProvider = [[VLCDialogProvider alloc] initWithLibrary:[VLCLibrary sharedLibrary] customUI:NO];

130
        _playbackSessionManagementLock = [[NSLock alloc] init];
Soomin Lee's avatar
Soomin Lee committed
131 132
        _shuffleMode = NO;
        _shuffleStack = [[NSMutableArray alloc] init];
Tobias's avatar
Tobias committed
133 134 135 136
    }
    return self;
}

137 138
#pragma mark - playback management

139
- (BOOL)_isMediaSuitableForDevice:(VLCMedia *)media
140
{
141
    NSArray *tracksInfo = media.tracksInformation;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
142
    double width = 0.0, height = 0.0;
143
    NSDictionary *track;
144

145 146 147 148 149 150 151
    for (NSUInteger x = 0; x < tracksInfo.count; x++) {
        track = tracksInfo[x];
        if ([track[VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
            width = [track[VLCMediaTracksInformationVideoWidth] doubleValue];
            height = [track[VLCMediaTracksInformationVideoHeight] doubleValue];
        }
    }
152

153
    NSUInteger totalNumberOfPixels = width * height;
154

155
    VLCSpeedCategory speedCategory = [[UIDevice currentDevice] vlcSpeedCategory];
156

157
    if (speedCategory == VLCSpeedCategoryTwoDevices) {
158
        return (totalNumberOfPixels < 922000); // 720p
159
    } else if (speedCategory == VLCSpeedCategoryThreeDevices) {
160
        return (totalNumberOfPixels < 2074000); // 1080p
161
    } else if (speedCategory == VLCSpeedCategoryFourDevices) {
162 163 164 165 166 167
        return (totalNumberOfPixels < 8850000); // 4K
    }

    return YES;
}

168
- (void)playMediaList:(VLCMediaList *)mediaList firstIndex:(NSInteger)index
169 170
{
    self.mediaList = mediaList;
171
    self.itemInMediaListToBePlayedFirst = (int)index;
172 173 174 175
    self.pathToExternalSubtitlesFile = nil;

    if (self.activePlaybackSession) {
        self.sessionWillRestart = YES;
176
        [self stopPlayback];
177 178
    } else {
        self.sessionWillRestart = NO;
179
        [self startPlayback];
180 181 182
    }
}

183 184 185 186 187 188 189 190
- (void)playURL:(NSURL *)url successCallback:(NSURL*)successCallback errorCallback:(NSURL *)errorCallback
{
    self.url = url;
    self.successCallback = successCallback;
    self.errorCallback = errorCallback;

    if (self.activePlaybackSession) {
        self.sessionWillRestart = YES;
191
        [self stopPlayback];
192 193
    } else {
        self.sessionWillRestart = NO;
194
        [self startPlayback];
195 196 197 198 199 200 201 202 203 204
    }
}

- (void)playURL:(NSURL *)url subtitlesFilePath:(NSString *)subsFilePath
{
    self.url = url;
    self.pathToExternalSubtitlesFile = subsFilePath;

    if (self.activePlaybackSession) {
        self.sessionWillRestart = YES;
205
        [self stopPlayback];
206 207
    } else {
        self.sessionWillRestart = NO;
208 209 210
        dispatch_async(dispatch_get_main_queue(), ^{
            [self startPlayback];
        });
211 212 213
    }
}

214 215
- (void)startPlayback
{
216 217
    if (_playerIsSetup) {
        APLog(@"%s: player is already setup, bailing out", __PRETTY_FUNCTION__);
218
        return;
219
    }
220 221 222 223 224 225 226

    BOOL ret = [_playbackSessionManagementLock tryLock];
    if (!ret) {
        APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
        return;
    }

227
    _activeSession = YES;
228

Felix Paul Kühne's avatar
Felix Paul Kühne committed
229
#if TARGET_OS_IOS
230
    [[AVAudioSession sharedInstance] setDelegate:self];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
231
#endif
232 233 234

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

235
    if (!self.url && !self.mediaList) {
236
        APLog(@"%s: no URL and no media list set, stopping playback", __PRETTY_FUNCTION__);
237
        [_playbackSessionManagementLock unlock];
238 239 240
        [self stopPlayback];
        return;
    }
241

242 243 244 245 246 247 248
    /* video decoding permanently fails if we don't provide a UIView to draw into on init
     * hence we provide one which is not attached to any view controller for off-screen drawing
     * and disable video decoding once playback started */
    _actualVideoOutputView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _actualVideoOutputView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _actualVideoOutputView.autoresizesSubviews = YES;

249 250 251 252 253 254 255 256 257 258
    if (self.pathToExternalSubtitlesFile)
        _listPlayer = [[VLCMediaListPlayer alloc] initWithOptions:@[[NSString stringWithFormat:@"--%@=%@", kVLCSettingSubtitlesFilePath, self.pathToExternalSubtitlesFile]] andDrawable:_actualVideoOutputView];
    else
        _listPlayer = [[VLCMediaListPlayer alloc] initWithDrawable:_actualVideoOutputView];

    /* to enable debug logging for the playback library instance, switch the boolean below
     * note that the library instance used for playback may not necessarily match the instance
     * used for media discovery or thumbnailing */
    _listPlayer.mediaPlayer.libraryInstance.debugLogging = NO;

259 260 261 262 263 264 265 266 267
    _mediaPlayer = _listPlayer.mediaPlayer;
    [_mediaPlayer setDelegate:self];
    if ([[defaults objectForKey:kVLCSettingPlaybackSpeedDefaultValue] floatValue] != 0)
        [_mediaPlayer setRate: [[defaults objectForKey:kVLCSettingPlaybackSpeedDefaultValue] floatValue]];
    if ([[defaults objectForKey:kVLCSettingDeinterlace] intValue] != 0)
        [_mediaPlayer setDeinterlaceFilter:@"blend"];
    else
        [_mediaPlayer setDeinterlaceFilter:nil];
    if (self.pathToExternalSubtitlesFile)
268
        [_mediaPlayer addPlaybackSlave:[NSURL fileURLWithPath:self.pathToExternalSubtitlesFile] type:VLCMediaPlaybackSlaveTypeSubtitle enforce:YES];
269 270

    VLCMedia *media;
271 272
    if (_mediaList) {
        media = [_mediaList mediaAtIndex:_itemInMediaListToBePlayedFirst];
273
        [media parseWithOptions:VLCMediaParseLocal];
274 275 276 277
        media.delegate = self;
    } else {
        media = [VLCMedia mediaWithURL:self.url];
        media.delegate = self;
278
        [media parseWithOptions:VLCMediaParseLocal];
279
        [media addOptions:self.mediaOptionsDictionary];
280
    }
281

282 283 284 285 286 287 288
    if (self.mediaList) {
        [_listPlayer setMediaList:self.mediaList];
    } else {
        [_listPlayer setRootMedia:media];
    }
    [_listPlayer setRepeatMode:VLCDoNotRepeat];

289 290
    [_playbackSessionManagementLock unlock];

291
    if (![self _isMediaSuitableForDevice:media]) {
292
#if TARGET_OS_IOS
293
        VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DEVICE_TOOSLOW_TITLE", nil)
294
                                                          message:[NSString stringWithFormat:NSLocalizedString(@"DEVICE_TOOSLOW", nil), [[UIDevice currentDevice] model], media.url.lastPathComponent]
295 296 297
                                                         delegate:self
                                                cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
                                                otherButtonTitles:NSLocalizedString(@"BUTTON_OPEN", nil), nil];
298
        [alert show];
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
#else
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"DEVICE_TOOSLOW_TITLE", nil)
                                                                       message:[NSString stringWithFormat:NSLocalizedString(@"DEVICE_TOOSLOW", nil), [[UIDevice currentDevice] model], media.url.lastPathComponent]
                                                                preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_OPEN", nil)
                                                                style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {
                                                                      [self _playNewMedia];
                                                              }];

        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
                                                               style:UIAlertActionStyleDestructive
                                                            handler:^(UIAlertAction * action) {
                                                                [self stopPlayback];
                                                            }];
        [alert addAction:defaultAction];
        [alert addAction:cancelAction];
317
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
318
#endif
319
    } else
320 321 322 323 324
        [self _playNewMedia];
}

- (void)_playNewMedia
{
325 326
    BOOL ret = [_playbackSessionManagementLock tryLock];
    if (!ret) {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
327
        APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
328 329 330
        return;
    }

331 332 333 334 335
    // Set last selected equalizer profile
    unsigned int profile = (unsigned int)[[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingEqualizerProfile] integerValue];
    [_mediaPlayer resetEqualizerFromProfile:profile];
    [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];

336 337
    _mediaWasJustStarted = YES;

338 339 340 341
    [_mediaPlayer addObserver:self forKeyPath:@"time" options:0 context:nil];
    [_mediaPlayer addObserver:self forKeyPath:@"remainingTime" options:0 context:nil];

    if (self.mediaList)
342
        [_listPlayer playItemAtNumber:@(self.itemInMediaListToBePlayedFirst)];
343 344 345 346 347 348
    else
        [_listPlayer playMedia:_listPlayer.rootMedia];

    if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
        [self.delegate prepareForMediaPlayback:self];

349
    _currentAspectRatio = VLCAspectRatioDefault;
350
    _mediaPlayer.videoAspectRatio = NULL;
351
    _mediaPlayer.scaleFactor = 0;
352 353

    [self subscribeRemoteCommands];
354

355
    _playerIsSetup = YES;
356 357

    [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidStart object:self];
358
    [_playbackSessionManagementLock unlock];
359 360
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
361
#if TARGET_OS_IOS
362 363 364 365
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
        [self _playNewMedia];
366
    else
367 368
        [self stopPlayback];
}
Felix Paul Kühne's avatar
Felix Paul Kühne committed
369
#endif
370 371 372

- (void)stopPlayback
{
373 374 375 376 377 378
    BOOL ret = [_playbackSessionManagementLock tryLock];
    if (!ret) {
        APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
        return;
    }

379 380 381 382 383 384 385 386 387 388 389
    if (_mediaPlayer) {
        @try {
            [_mediaPlayer removeObserver:self forKeyPath:@"time"];
            [_mediaPlayer removeObserver:self forKeyPath:@"remainingTime"];
        }
        @catch (NSException *exception) {
            APLog(@"we weren't an observer yet");
        }

        if (_mediaPlayer.media) {
            [_mediaPlayer pause];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
390
#if TARGET_OS_IOS
391
            [self _savePlaybackState];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
392
#endif
393 394 395 396 397 398 399
            [_mediaPlayer stop];
        }
        if (_mediaPlayer)
            _mediaPlayer = nil;
        if (_listPlayer)
            _listPlayer = nil;
    }
400 401 402 403 404 405 406 407 408 409 410
    if (!_sessionWillRestart) {
        if (_mediaList)
            _mediaList = nil;
        if (_url)
            _url = nil;
        if (_pathToExternalSubtitlesFile) {
            NSFileManager *fileManager = [NSFileManager defaultManager];
            if ([fileManager fileExistsAtPath:_pathToExternalSubtitlesFile])
                [fileManager removeItemAtPath:_pathToExternalSubtitlesFile error:nil];
            _pathToExternalSubtitlesFile = nil;
        }
411 412
    }
    _playerIsSetup = NO;
Soomin Lee's avatar
Soomin Lee committed
413
    [_shuffleStack removeAllObjects];
414

415
    if (self.errorCallback && _playbackFailed && !_sessionWillRestart)
416
        [[UIApplication sharedApplication] openURL:self.errorCallback];
417
    else if (self.successCallback && !_sessionWillRestart)
418 419
        [[UIApplication sharedApplication] openURL:self.successCallback];

420 421
    [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = nil;
    [self unsubscribeFromRemoteCommand];
422
    _activeSession = NO;
423

424
    [_playbackSessionManagementLock unlock];
425 426
    if (_playbackFailed) {
        [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidFail object:self];
427
    } else if (!_sessionWillRestart) {
428
        [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidStop object:self];
429 430
    } else {
        self.sessionWillRestart = NO;
431
        [self startPlayback];
432
    }
433 434
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
435
#if TARGET_OS_IOS
436 437
- (void)_savePlaybackState
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
438 439 440 441 442 443 444
    @try {
        [[MLMediaLibrary sharedMediaLibrary] save];
    }
    @catch (NSException *exception) {
        APLog(@"saving playback state failed");
    }

445 446 447 448
    MLFile *fileItem;
    NSArray *files = [MLFile fileForURL:_mediaPlayer.media.url];
    if (files.count > 0)
        fileItem = files.firstObject;
449

450 451
    if (!fileItem) {
        APLog(@"couldn't find file, not saving playback progress");
452
        return;
453
    }
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480

    @try {
        float position = _mediaPlayer.position;
        fileItem.lastPosition = @(position);
        fileItem.lastAudioTrack = @(_mediaPlayer.currentAudioTrackIndex);
        fileItem.lastSubtitleTrack = @(_mediaPlayer.currentVideoSubTitleIndex);

        if (position > .95)
            return;

        NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString* newThumbnailPath = [searchPaths[0] stringByAppendingPathComponent:@"VideoSnapshots"];
        NSFileManager *fileManager = [NSFileManager defaultManager];

        if (![fileManager fileExistsAtPath:newThumbnailPath])
            [fileManager createDirectoryAtPath:newThumbnailPath withIntermediateDirectories:YES attributes:nil error:nil];

        newThumbnailPath = [newThumbnailPath stringByAppendingPathComponent:fileItem.objectID.URIRepresentation.lastPathComponent];
        [_mediaPlayer saveVideoSnapshotAt:newThumbnailPath withWidth:0 andHeight:0];

        _recheckForExistingThumbnail = YES;
        [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:.25];
    }
    @catch (NSException *exception) {
        APLog(@"failed to save current media state - file removed?");
    }
}
Felix Paul Kühne's avatar
Felix Paul Kühne committed
481
#endif
482

Felix Paul Kühne's avatar
Felix Paul Kühne committed
483
#if TARGET_OS_IOS
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
- (void)_updateStoredThumbnailForFile:(MLFile *)fileItem
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString* newThumbnailPath = [searchPaths[0] stringByAppendingPathComponent:@"VideoSnapshots"];
    newThumbnailPath = [newThumbnailPath stringByAppendingPathComponent:fileItem.objectID.URIRepresentation.lastPathComponent];

    if (![fileManager fileExistsAtPath:newThumbnailPath]) {
        if (_recheckForExistingThumbnail) {
            [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:1.];
            _recheckForExistingThumbnail = NO;
        } else
            return;
    }

    UIImage *newThumbnail = [UIImage imageWithContentsOfFile:newThumbnailPath];
    if (!newThumbnail) {
        if (_recheckForExistingThumbnail) {
            [self performSelector:@selector(_updateStoredThumbnailForFile:) withObject:fileItem afterDelay:1.];
            _recheckForExistingThumbnail = NO;
        } else
            return;
    }

    @try {
        [fileItem setComputedThumbnailScaledForDevice:newThumbnail];
    }
    @catch (NSException *exception) {
        APLog(@"updating thumbnail failed");
    }

    [fileManager removeItemAtPath:newThumbnailPath error:nil];
516
}
Felix Paul Kühne's avatar
Felix Paul Kühne committed
517
#endif
518 519 520

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
521 522
    if (_mediaWasJustStarted) {
        _mediaWasJustStarted = NO;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
523
#if TARGET_OS_IOS
524 525 526 527 528 529
        if (self.mediaList) {
            MLFile *item;
            NSArray *matches = [MLFile fileForURL:_mediaPlayer.media.url];
            item = matches.firstObject;
            [self _recoverLastPlaybackStateOfItem:item];
        }
530 531 532
#else
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        BOOL bValue = [defaults boolForKey:kVLCSettingUseSPDIF];
533

534
        if (bValue) {
535
           _mediaPlayer.audio.passthrough = bValue;
536
        }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
537
#endif
538 539
    }

540 541
    if ([self.delegate respondsToSelector:@selector(playbackPositionUpdated:)])
        [self.delegate playbackPositionUpdated:self];
542 543 544

    [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackPositionUpdated
                                                        object:self];
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
}

- (NSInteger)mediaDuration
{
    return _listPlayer.mediaPlayer.media.length.intValue;;
}

- (BOOL)isPlaying
{
    return _mediaPlayer.isPlaying;
}

- (VLCRepeatMode)repeatMode
{
    return _listPlayer.repeatMode;
}

- (void)setRepeatMode:(VLCRepeatMode)repeatMode
{
    _listPlayer.repeatMode = repeatMode;
}

- (BOOL)currentMediaHasChapters
{
569
    return [_mediaPlayer numberOfTitles] > 1 || [_mediaPlayer numberOfChaptersForTitle:_mediaPlayer.currentTitleIndex] > 1;
570 571 572 573 574 575 576
}

- (BOOL)currentMediaHasTrackToChooseFrom
{
    return [[_mediaPlayer audioTrackIndexes] count] > 2 || [[_mediaPlayer videoSubTitlesIndexes] count] > 1;
}

577 578
- (BOOL)activePlaybackSession
{
579
    return _activeSession;
580 581 582 583 584 585 586
}

- (BOOL)audioOnlyPlaybackSession
{
    return _mediaIsAudioOnly;
}

587 588 589 590 591
- (NSString *)mediaTitle
{
    return _title;
}

592 593 594
- (float)playbackRate
{
    float f_rate = _mediaPlayer.rate;
595 596
    _currentPlaybackRate = f_rate;
    return f_rate;
597 598 599 600 601 602 603 604 605
}

- (void)setPlaybackRate:(float)playbackRate
{
    if (_currentPlaybackRate != playbackRate)
        [_mediaPlayer setRate:playbackRate];
    _currentPlaybackRate = playbackRate;
}

606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
- (void)setAudioDelay:(float)audioDelay
{
    _mediaPlayer.currentAudioPlaybackDelay = 1000000.*audioDelay;
}
- (float)audioDelay
{
    return _mediaPlayer.currentAudioPlaybackDelay/1000000.;
}
-(void)setSubtitleDelay:(float)subtitleDeleay
{
    _mediaPlayer.currentVideoSubTitleDelay = 1000000.*subtitleDeleay;
}
- (float)subtitleDelay
{
    return _mediaPlayer.currentVideoSubTitleDelay/1000000.;
}

623 624 625
- (void)mediaPlayerStateChanged:(NSNotification *)aNotification
{
    VLCMediaPlayerState currentState = _mediaPlayer.state;
626

627 628 629 630 631
    if (currentState == VLCMediaPlayerStateBuffering) {
        /* attach delegate */
        _mediaPlayer.media.delegate = self;

        /* on-the-fly values through hidden API */
632 633 634 635 636
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [_mediaPlayer performSelector:@selector(setTextRendererFont:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFont]];
        [_mediaPlayer performSelector:@selector(setTextRendererFontSize:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFontSize]];
        [_mediaPlayer performSelector:@selector(setTextRendererFontColor:) withObject:[defaults objectForKey:kVLCSettingSubtitlesFontColor]];
        [_mediaPlayer performSelector:@selector(setTextRendererFontForceBold:) withObject:[defaults objectForKey:kVLCSettingSubtitlesBoldFont]];
637
    } else if (currentState == VLCMediaPlayerStateError) {
638
        APLog(@"Playback failed");
639
        _playbackFailed = YES;
640
        self.sessionWillRestart = NO;
641
        [self stopPlayback];
642
    } else if (currentState == VLCMediaPlayerStateEnded || currentState == VLCMediaPlayerStateStopped) {
643 644
        [_listPlayer.mediaList lock];
        NSUInteger listCount = _listPlayer.mediaList.count;
645
        if ([_listPlayer.mediaList indexOfMedia:_mediaPlayer.media] == listCount - 1 && self.repeatMode == VLCDoNotRepeat) {
646
            [_listPlayer.mediaList unlock];
647
            self.sessionWillRestart = NO;
648 649
            [self stopPlayback];
            return;
650 651 652
        } else if (listCount > 1) {
            [_listPlayer.mediaList unlock];
            [_listPlayer next];
653 654
        } else
            [_listPlayer.mediaList unlock];
655 656
    }

657 658 659 660 661 662
    if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
        [self.delegate mediaPlayerStateChanged:currentState
                                     isPlaying:_mediaPlayer.isPlaying
              currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
                       currentMediaHasChapters:self.currentMediaHasChapters
                         forPlaybackController:self];
663 664

    [self setNeedsMetadataUpdate];
665 666 667 668 669
}

#pragma mark - playback controls
- (void)playPause
{
670
    if ([_mediaPlayer isPlaying]) {
671
        [_listPlayer pause];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
672
#if TARGET_OS_IOS
673
        [self _savePlaybackState];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
674
#endif
675 676
        [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
    } else {
677
        [_listPlayer play];
678 679
        [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidResume object:self];
    }
680 681 682 683
}

- (void)forward
{
Soomin Lee's avatar
Soomin Lee committed
684 685
    NSInteger mediaListCount = _mediaList.count;

Soomin Lee's avatar
Soomin Lee committed
686
#if TARGET_OS_IOS
Soomin Lee's avatar
Soomin Lee committed
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
    if (mediaListCount > 2 && _shuffleMode) {

        NSNumber *nextIndex;
        NSUInteger currentIndex = [_mediaList indexOfMedia:_listPlayer.mediaPlayer.media];

        //Reached end of playlist
        if (_shuffleStack.count + 1 == mediaListCount) {
            if ([self repeatMode] == VLCDoNotRepeat)
                return;
            [_shuffleStack removeAllObjects];
        }

        [_shuffleStack addObject:[NSNumber numberWithUnsignedInteger:currentIndex]];
        do {
            nextIndex = [NSNumber numberWithUnsignedInt:arc4random_uniform((uint32_t)mediaListCount)];
        } while (currentIndex == nextIndex.unsignedIntegerValue || [_shuffleStack containsObject:nextIndex]);

        [_listPlayer playItemAtNumber:[NSNumber numberWithUnsignedInteger:nextIndex.unsignedIntegerValue]];
        [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];

        return;
    }
Soomin Lee's avatar
Soomin Lee committed
709
#endif
Soomin Lee's avatar
Soomin Lee committed
710 711

    if (mediaListCount > 1) {
712
        [_listPlayer next];
713
        [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
714 715 716 717 718 719 720 721
    } else {
        NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackForwardSkipLength];
        [_mediaPlayer jumpForward:skipLength.intValue];
    }
}

- (void)backward
{
722
    if (_mediaList.count > 1) {
723
        [_listPlayer previous];
724
        [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
725 726 727 728 729 730 731 732 733
    }
    else {
        NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackBackwardSkipLength];
        [_mediaPlayer jumpBackward:skipLength.intValue];
    }
}

- (void)switchAspectRatio
{
734
    if (_currentAspectRatio == VLCAspectRatioSixteenToTen) {
735
        _mediaPlayer.videoAspectRatio = NULL;
736 737
        _mediaPlayer.scaleFactor = 0;
        _currentAspectRatio = VLCAspectRatioDefault;
738
    } else {
739
        _currentAspectRatio++;
740

741
        if (_currentAspectRatio == VLCAspectRatioFillToScreen) {
742
            UIScreen *screen;
743
            if (![[UIDevice currentDevice] VLCHasExternalDisplay])
744 745 746 747 748 749
                screen = [UIScreen mainScreen];
            else
                screen = [UIScreen screens][1];

            float f_ar = screen.bounds.size.width / screen.bounds.size.height;

750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
            if (f_ar == (float)(4.0/3.0) ||
                f_ar == (float)(1366./1024.)) {
                // all iPads
                _mediaPlayer.videoCropGeometry = "4:3";
            } else if (f_ar == (float)(2./3.) || f_ar == (float)(480./320.)) {
                // all other iPhones
                _mediaPlayer.videoCropGeometry = "16:10"; // libvlc doesn't support 2:3 crop
            } else if (f_ar == .5625) {
                // AirPlay
                _mediaPlayer.videoCropGeometry = "16:9";
            } else if (f_ar == (float)(640./1136.) ||
                       f_ar == (float)(568./320.) ||
                       f_ar == (float)(667./375.) ||
                       f_ar == (float)(736./414.)) {
                // iPhone 5 and 6 and 6+
                _mediaPlayer.videoCropGeometry = "16:9";
766
            } else
767
                APLog(@"unknown screen format %f, can't crop", f_ar);
768 769
        } else {
            _mediaPlayer.videoAspectRatio = (char *)[[self stringForAspectRatio:_currentAspectRatio] UTF8String];
770
            _mediaPlayer.videoCropGeometry = NULL;
771
        }
772
    }
773

774 775 776 777
    if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)]) {
        [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), [self stringForAspectRatio:_currentAspectRatio]] forPlaybackController:self];
    }
}
778

779 780 781 782 783 784 785 786
- (NSString *)stringForAspectRatio:(VLCAspectRatio)ratio
{
    switch (ratio) {
            case VLCAspectRatioFillToScreen:
            return NSLocalizedString(@"FILL_TO_SCREEN", nil);
            case VLCAspectRatioDefault:
            return NSLocalizedString(@"DEFAULT", nil);
            case VLCAspectRatioFourToThree:
787
            return @"4:3";
788
            case VLCAspectRatioSixteenToTen:
789
            return @"16:10";
790
            case VLCAspectRatioSixteenToNine:
791
            return @"16:9";
792 793
        default:
            NSAssert(NO, @"this shouldn't happen");
794 795 796 797 798 799
    }
}

- (void)setVideoOutputView:(UIView *)videoOutputView
{
    if (videoOutputView) {
800 801 802
        if ([_actualVideoOutputView superview] != nil)
            [_actualVideoOutputView removeFromSuperview];

803 804
        _actualVideoOutputView.frame = (CGRect){CGPointZero, videoOutputView.frame.size};

805 806 807
        if (_mediaPlayer.currentVideoTrackIndex == -1)
            _mediaPlayer.currentVideoTrackIndex = 0;

808
        [videoOutputView addSubview:_actualVideoOutputView];
809 810 811
        [_actualVideoOutputView layoutSubviews];
        [_actualVideoOutputView updateConstraints];
        [_actualVideoOutputView setNeedsLayout];
812
    } else
813 814 815 816 817 818 819 820 821 822
        [_actualVideoOutputView removeFromSuperview];

    _videoOutputViewWrapper = videoOutputView;
}

- (UIView *)videoOutputView
{
    return _videoOutputViewWrapper;
}

823
#pragma mark - 360 Support
Soomin Lee's avatar
Soomin Lee committed
824
#if !TARGET_OS_TV
825 826 827 828 829 830 831 832 833 834 835 836 837
- (BOOL)updateViewpoint:(CGFloat)yaw pitch:(CGFloat)pitch roll:(CGFloat)roll fov:(CGFloat)fov absolute:(BOOL)absolute
{
    return [_mediaPlayer updateViewpoint:yaw pitch:pitch roll:roll fov:fov absolute:absolute];
}

- (NSInteger)currentMediaProjection
{
    VLCMedia *media = [_mediaPlayer media];
    NSInteger currentVideoTrackIndex = [_mediaPlayer currentVideoTrackIndex];

    if (media && currentVideoTrackIndex >= 0) {
        NSArray *tracksInfo = media.tracksInformation;

838 839 840 841
        for (NSDictionary *track in tracksInfo) {
            if ([track[VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
                return [track[VLCMediaTracksInformationVideoProjection] integerValue];
            }
842 843 844 845
        }
    }
    return -1;
}
Soomin Lee's avatar
Soomin Lee committed
846
#endif
847

848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
#pragma mark - equalizer

- (void)setAmplification:(CGFloat)amplification forBand:(unsigned int)index
{
    if (!_mediaPlayer.equalizerEnabled)
        [_mediaPlayer setEqualizerEnabled:YES];

    [_mediaPlayer setAmplification:amplification forBand:index];

    // For some reason we have to apply again preamp to apply change
    [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];
}

- (CGFloat)amplificationOfBand:(unsigned int)index
{
    return [_mediaPlayer amplificationOfBand:index];
}

- (NSArray *)equalizerProfiles
{
    return _mediaPlayer.equalizerProfiles;
}

- (void)resetEqualizerFromProfile:(unsigned int)profile
{
    [[NSUserDefaults standardUserDefaults] setObject:@(profile) forKey:kVLCSettingEqualizerProfile];
    [_mediaPlayer resetEqualizerFromProfile:profile];
}

- (void)setPreAmplification:(CGFloat)preAmplification
{
    if (!_mediaPlayer.equalizerEnabled)
        [_mediaPlayer setEqualizerEnabled:YES];

    [_mediaPlayer setPreAmplification:preAmplification];
}

- (CGFloat)preAmplification
{
    return [_mediaPlayer preAmplification];
}

#pragma mark - AVSession delegate
- (void)beginInterruption
{
    if ([_mediaPlayer isPlaying]) {
        [_mediaPlayer pause];
895
        _shouldResumePlayingAfterInteruption = YES;
896 897 898 899 900
    }
}

- (void)endInterruption
{
901
    if (_shouldResumePlayingAfterInteruption) {
902
        [_mediaPlayer play];
903
        _shouldResumePlayingAfterInteruption = NO;
904 905 906
    }
}

907
- (BOOL)areHeadphonesPlugged
908 909
{
    NSArray *outputs = [[AVAudioSession sharedInstance] currentRoute].outputs;
910
    NSString *portName = [[outputs firstObject] portName];
911 912 913 914 915
    return [portName isEqualToString:@"Headphones"];
}

- (void)audioSessionRouteChange:(NSNotification *)notification
{
916 917 918 919 920 921
    NSDictionary *userInfo = notification.userInfo;
    NSInteger routeChangeReason = [[userInfo valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];

    if (routeChangeReason == AVAudioSessionRouteChangeReasonRouteConfigurationChange)
        return;

922
    BOOL headphonesPlugged = [self areHeadphonesPlugged];
923

924
    if (_headphonesWasPlugged && !headphonesPlugged && [_mediaPlayer isPlaying]) {
925
        [_mediaPlayer pause];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
926
#if TARGET_OS_IOS
927
        [self _savePlaybackState];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
928
#endif
929 930
        [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
    }
931
    _headphonesWasPlugged = headphonesPlugged;
932 933 934 935
}

#pragma mark - Managing the media item

Felix Paul Kühne's avatar
Felix Paul Kühne committed
936
#if TARGET_OS_IOS
937
- (MLFile *)currentlyPlayingMediaFile {
938
    if (self.mediaList) {
939
        NSArray *results = [MLFile fileForURL:_mediaPlayer.media.url];
940
        return results.firstObject;
941 942 943 944
    }

    return nil;
}
Felix Paul Kühne's avatar
Felix Paul Kühne committed
945
#endif
946 947 948 949

#pragma mark - metadata handling
- (void)mediaDidFinishParsing:(VLCMedia *)aMedia
{
950
    [self setNeedsMetadataUpdate];
951 952 953 954
}

- (void)mediaMetaDataDidChange:(VLCMedia*)aMedia
{
955 956 957 958 959 960 961
    [self setNeedsMetadataUpdate];
}

- (void)setNeedsMetadataUpdate
{
    if (_needsMetadataUpdate == NO) {
        _needsMetadataUpdate = YES;
962
        dispatch_async(dispatch_get_main_queue(), ^{
963 964 965
            [self _updateDisplayedMetadata];
        });
    }
966 967 968 969
}

- (void)_updateDisplayedMetadata
{
970 971
    _needsMetadataUpdate = NO;

972
    NSNumber *trackNumber;
973 974 975 976 977

    NSString *title;
    NSString *artist;
    NSString *albumName;
    UIImage* artworkImage;
978
    BOOL mediaIsAudioOnly = NO;
979

Felix Paul Kühne's avatar
Felix Paul Kühne committed
980 981 982
#if TARGET_OS_IOS
    MLFile *item;

983
    if (self.mediaList) {
984
        NSArray *matches = [MLFile fileForURL:_mediaPlayer.media.url];
985
        item = matches.firstObject;
986 987 988 989
    }

    if (item) {
        if (item.isAlbumTrack) {
990 991 992
            title = item.albumTrack.title;
            artist = item.albumTrack.artist;
            albumName = item.albumTrack.album.name;
993
        } else
994
            title = item.title;
995 996

        /* MLKit knows better than us if this thing is audio only or not */
997
        mediaIsAudioOnly = [item isSupportedAudioFile];
998
    } else {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
999
#endif
1000 1001
        NSDictionary * metaDict = _mediaPlayer.media.metaDictionary;

1002 1003 1004 1005 1006 1007
        if (metaDict) {
            title = metaDict[VLCMetaInformationNowPlaying] ? metaDict[VLCMetaInformationNowPlaying] : metaDict[VLCMetaInformationTitle];
            artist = metaDict[VLCMetaInformationArtist];
            albumName = metaDict[VLCMetaInformationAlbum];
            trackNumber = metaDict[VLCMetaInformationTrackNumber];
        }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
1008
#if TARGET_OS_IOS
1009
    }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
1010
#endif
1011 1012 1013 1014 1015

    if (!mediaIsAudioOnly) {
        /* either what we are playing is not a file known to MLKit or
         * MLKit fails to acknowledge that it is audio-only.
         * Either way, do a more expensive check to see if it is really audio-only */
1016 1017
        NSArray *tracks = _mediaPlayer.media.tracksInformation;
        NSUInteger trackCount = tracks.count;
1018
        mediaIsAudioOnly = YES;
1019 1020
        for (NSUInteger x = 0 ; x < trackCount; x++) {
            if ([[tracks[x] objectForKey:VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
1021
                mediaIsAudioOnly = NO;
1022 1023 1024 1025 1026
                break;
            }
        }
    }

1027
    if (mediaIsAudioOnly) {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
1028
#if TARGET_OS_IOS
1029 1030
        artworkImage = [VLCThumbnailsCache thumbnailForManagedObject:item];

1031 1032 1033 1034 1035
        if (artworkImage) {
            if (artist)
                title = [title stringByAppendingFormat:@" — %@", artist];
            if (albumName)
                title = [title stringByAppendingFormat:@" — %@", albumName];
1036
        }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
1037
#endif
1038

1039 1040
        if (title.length < 1)
            title = [[_mediaPlayer.media url] lastPathComponent];
1041 1042 1043 1044 1045
    }

    /* populate delegate with metadata info */
    if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:title:artwork:artist:album:audioOnly:)])
        [self.delegate displayMetadataForPlaybackController:self
1046 1047 1048 1049 1050
                                                      title:title
                                                    artwork:artworkImage
                                                     artist:artist
                                                      album:albumName
                                                  audioOnly:mediaIsAudioOnly];
1051 1052 1053 1054 1055 1056 1057 1058

    /* populate now playing info center with metadata information */
    NSMutableDictionary *currentlyPlayingTrackInfo = [NSMutableDictionary dictionary];
    currentlyPlayingTrackInfo[MPMediaItemPropertyPlaybackDuration] = @(_mediaPlayer.media.length.intValue / 1000.);
    currentlyPlayingTrackInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] =  @(_mediaPlayer.time.intValue / 1000.);
    currentlyPlayingTrackInfo[MPNowPlayingInfoPropertyPlaybackRate] = @(_mediaPlayer.isPlaying ? _mediaPlayer.rate : 0.0);

    /* don't leak sensitive information to the OS, if passcode lock is enabled */
Felix Paul Kühne's avatar
Felix Paul Kühne committed
1059
#if TARGET_OS_IOS
1060
    if (![[VLCKeychainCoordinator defaultCoordinator] passcodeLockEnabled]) {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
1061
#endif
1062 1063 1064 1065 1066 1067
        if (title)
            currentlyPlayingTrackInfo[MPMediaItemPropertyTitle] = title;
        if (artist.length > 0)
            currentlyPlayingTrackInfo[MPMediaItemPropertyArtist] = artist;
        if (albumName.length > 0)
            currentlyPlayingTrackInfo[MPMediaItemPropertyAlbumTitle] = albumName;
1068 1069 1070 1071

        if ([trackNumber intValue] > 0)
            currentlyPlayingTrackInfo[MPMediaItemPropertyAlbumTrackNumber] = trackNumber;

Felix Paul Kühne's avatar
Felix Paul Kühne committed
1072
#if TARGET_OS_IOS
1073 1074 1075 1076 1077 1078 1079 1080
        /* FIXME: UGLY HACK
         * iOS 8.2 and 8.3 include an issue which will lead to a termination of the client app if we set artwork
         * when the playback initialized through the watch extension
         * radar://pending */
        if ([WKInterfaceDevice class] != nil) {
            if ([WKInterfaceDevice currentDevice] != nil)
                goto setstuff;
        }
1081 1082
        if (artworkImage) {
            MPMediaItemArtwork *mpartwork = [[MPMediaItemArtwork alloc] initWithImage:artworkImage];
1083 1084 1085
            currentlyPlayingTrackInfo[MPMediaItemPropertyArtwork] = mpartwork;
        }
    }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
1086
#endif
1087 1088 1089

setstuff:
    [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = currentlyPlayingTrackInfo;
1090
    [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
1091 1092 1093 1094 1095 1096

    _title = title;
    _artist = artist;
    _albumName = albumName;
    _artworkImage = artworkImage;
    _mediaIsAudioOnly = mediaIsAudioOnly;
1097 1098
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
1099
#if TARGET_OS_IOS
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
- (void)_recoverLastPlaybackStateOfItem:(MLFile *)item
{
    if (item) {
        if (_mediaPlayer.numberOfAudioTracks > 2) {
            if (item.lastAudioTrack.intValue > 0)
                _mediaPlayer.currentAudioTrackIndex = item.lastAudioTrack.intValue;
        }
        if (_mediaPlayer.numberOfSubtitlesTracks > 2) {
            if (item.lastSubtitleTrack.intValue > 0)
                _mediaPlayer.currentVideoSubTitleIndex = item.lastSubtitleTrack.intValue;
        }

        CGFloat lastPosition = .0;
        NSInteger duration = 0;

        if (item.lastPosition)
            lastPosition = item.lastPosition.floatValue;
        duration = item.duration.intValue;

1119 1120
        if (lastPosition < .95 && _mediaPlayer.position < lastPosition && (duration * lastPosition - duration) < -50000) {
            NSInteger continuePlayback;
1121
            if ([item isAlbumTrack] || [item isSupportedAudioFile])
1122 1123 1124 1125
                continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioPlayback] integerValue];
            else
                continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinuePlayback] integerValue];

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
            if (continuePlayback == 1) {
                _mediaPlayer.position = lastPosition;
            } else if (continuePlayback == 0) {
                VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"CONTINUE_PLAYBACK", nil)
                                                                  message:[NSString stringWithFormat:NSLocalizedString(@"CONTINUE_PLAYBACK_LONG", nil), item.title]
                                                                 delegate:self
                                                        cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
                                                        otherButtonTitles:NSLocalizedString(@"BUTTON_CONTINUE", nil), nil];
                alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
                    if (!cancelled) {
                        _mediaPlayer.position = lastPosition;
                    }
                };
                [alert show];
            }
        }
1142 1143
    }
}
Felix Paul Kühne's avatar
Felix Paul Kühne committed
1144
#endif
1145

1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
- (void)recoverDisplayedMetadata
{
    if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:title:artwork:artist:album:audioOnly:)])
        [self.delegate displayMetadataForPlaybackController:self
                                                      title:_title
                                                    artwork:_artworkImage
                                                     artist:_artist
                                                      album:_albumName
                                                  audioOnly:_mediaIsAudioOnly];
}

1157 1158 1159 1160 1161 1162 1163 1164
- (void)recoverPlaybackState
{
    if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
        [self.delegate mediaPlayerStateChanged:_mediaPlayer.state
                                     isPlaying:self.isPlaying
              currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
                       currentMediaHasChapters:self.currentMediaHasChapters
                         forPlaybackController:self];
1165 1166
    if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
        [self.delegate prepareForMediaPlayback:self];
1167 1168
}

1169 1170 1171 1172 1173 1174 1175 1176 1177
- (void)scheduleSleepTimerWithInterval:(NSTimeInterval)timeInterval
{
    if (_sleepTimer) {
        [_sleepTimer invalidate];
        _sleepTimer = nil;
    }
    _sleepTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(stopPlayback) userInfo:nil repeats:NO];
}

1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
#pragma mark - remote events

static inline NSArray * RemoteCommandCenterCommandsToHandle(MPRemoteCommandCenter *cc)
{
    /* commmented out other available commands which we don't support now but may
     * support at some point in the future */
    return @[cc.pauseCommand, cc.playCommand, cc.stopCommand, cc.togglePlayPauseCommand,
             cc.nextTrackCommand, cc.previousTrackCommand,
             cc.skipForwardCommand, cc.skipBackwardCommand,
             //             cc.seekForwardCommand, cc.seekBackwardCommand,
             //             cc.ratingCommand,
             cc.changePlaybackRateCommand,
             //             cc.likeCommand,cc.dislikeCommand,cc.bookmarkCommand,
             ];
}

- (void)subscribeRemoteCommands
{
    /* pre iOS 7.1 */
    if (![MPRemoteCommandCenter class]) {
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        return;
    }
    /* for iOS 7.1 and above: */

    MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];

    /*
     * since the control center and lockscreen shows only either skipForward/Backward
     * or next/previousTrack buttons but prefers skip buttons,
     * we only enable skip buttons if we have a no medialist
     */
1210
    BOOL enableSkip = [VLCPlaybackController sharedInstance].mediaList.count <= 1;
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
    commandCenter.skipForwardCommand.enabled = enableSkip;
    commandCenter.skipBackwardCommand.enabled = enableSkip;

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSNumber *forwardSkip = [defaults valueForKey:kVLCSettingPlaybackForwardSkipLength];
    commandCenter.skipForwardCommand.preferredIntervals = @[forwardSkip];
    NSNumber *backwardSkip = [defaults valueForKey:kVLCSettingPlaybackBackwardSkipLength];
    commandCenter.skipBackwardCommand.preferredIntervals = @[backwardSkip];

    NSArray *supportedPlaybackRates = @[@(0.5),@(0.75),@(1.0),@(1.25),@(1.5),@(1.75),@(2.0)];
    commandCenter.changePlaybackRateCommand.supportedPlaybackRates = supportedPlaybackRates;

    NSArray *commandsToSubscribe = RemoteCommandCenterCommandsToHandle(commandCenter);
    for (MPRemoteCommand *command in commandsToSubscribe) {
        [command addTarget:self action:@selector(remoteCommandEvent:)];
    }
}

- (void)unsubscribeFromRemoteCommand
{
    /* pre iOS 7.1 */
    if (![MPRemoteCommandCenter class]) {
        [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
        return;
    }

    /* for iOS 7.1 and above: */
    MPRemoteCommandCenter *cc = [MPRemoteCommandCenter sharedCommandCenter];
    NSArray *commmandsToRemoveFrom = RemoteCommandCenterCommandsToHandle(cc);
    for (MPRemoteCommand *command in commmandsToRemoveFrom) {
        [command removeTarget:self];
    }
}

- (MPRemoteCommandHandlerStatus )remoteCommandEvent:(MPRemoteCommandEvent *)event
{
    MPRemoteCommandCenter *cc = [MPRemoteCommandCenter sharedCommandCenter];
    MPRemoteCommandHandlerStatus result = MPRemoteCommandHandlerStatusSuccess;

    if (event.command == cc.pauseCommand) {
        [_listPlayer pause];
    } else if (event.command == cc.playCommand) {
        [_listPlayer play];
    } else if (event.command == cc.stopCommand) {
        [_listPlayer stop];
    } else if (event.command == cc.togglePlayPauseCommand) {
        [self playPause];
    } else if (event.command == cc.nextTrackCommand) {
        result = [_listPlayer next] ? MPRemoteCommandHandlerStatusSuccess : MPRemoteCommandHandlerStatusNoSuchContent;
    } else if (event.command == cc.previousTrackCommand) {
        result = [_listPlayer previous] ? MPRemoteCommandHandlerStatusSuccess : MPRemoteCommandHandlerStatusNoSuchContent;
    } else if (event.command == cc.skipForwardCommand) {
        if ([event isKindOfClass:[MPSkipIntervalCommandEvent class]]) {
            MPSkipIntervalCommandEvent *skipEvent = (MPSkipIntervalCommandEvent *)event;
            [_mediaPlayer jumpForward:skipEvent.interval];
        } else {
            result = MPRemoteCommandHandlerStatusCommandFailed;
        }
    } else if (event.command == cc.skipBackwardCommand) {
        if ([event isKindOfClass:[MPSkipIntervalCommandEvent class]]) {
            MPSkipIntervalCommandEvent *skipEvent = (MPSkipIntervalCommandEvent *)event;
            [_mediaPlayer jumpBackward:skipEvent.interval];
        } else {
            result = MPRemoteCommandHandlerStatusCommandFailed;
        }
    } else if (event.command == cc.changePlaybackRateCommand) {
        if ([event isKindOfClass:[MPChangePlaybackRateCommandEvent class]]) {
            MPChangePlaybackRateCommandEvent *rateEvent = (MPChangePlaybackRateCommandEvent *)event;
            [_mediaPlayer setRate:rateEvent.playbackRate];
        } else {
            result = MPRemoteCommandHandlerStatusCommandFailed;
        }
        /* stubs for when we want to support the other available commands */
        //    } else if (event.command == cc.seekForwardCommand) {
        //    } else if (event.command == cc.seekBackwardCommand) {
        //    } else if (event.command == cc.ratingCommand) {
        //    } else if (event.command == cc.likeCommand) {
        //    } else if (event.command == cc.dislikeCommand) {
        //    } else if (event.command == cc.bookmarkCommand) {
    } else {
        APLog(@"%s Unsupported remote control event: %@",__PRETTY_FUNCTION__,event);
        result = MPRemoteCommandHandlerStatusCommandFailed;
    }

    if (result == MPRemoteCommandHandlerStatusCommandFailed)
        APLog(@"%s Wasn't able to handle remote control event: %@",__PRETTY_FUNCTION__,event);

    return result;
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlPlay:
            [_listPlayer play];
            break;

        case UIEventSubtypeRemoteControlPause:
            [_listPlayer pause];
            break;

        case UIEventSubtypeRemoteControlTogglePlayPause:
            [self playPause];
            break;

        case UIEventSubtypeRemoteControlNextTrack:
            [self forward];
            break;

        case UIEventSubtypeRemoteControlPreviousTrack:
            [self backward];
            break;

        case UIEventSubtypeRemoteControlStop:
            [self stopPlayback];
            break;

        default:
            break;
    }
}

#pragma mark - background interaction

- (void)applicationWillResignActive:(NSNotification *)aNotification
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
1337
#if TARGET_OS_IOS
1338
    [self _savePlaybackState];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
1339
#endif
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350

    if (![[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioInBackgroundKey] boolValue]) {
        if ([_mediaPlayer isPlaying]) {
            [_mediaPlayer pause];
            _shouldResumePlaying = YES;
        }
    }
}

- (void)applicationDidEnterBackground:(NSNotification *)notification
{
1351 1352 1353 1354
    _preBackgroundWrapperView = _videoOutputViewWrapper;

    if (_mediaPlayer.audioTrackIndexes.count > 0)
        _mediaPlayer.currentVideoTrackIndex = -1;
1355 1356 1357 1358
}

- (void)applicationDidBecomeActive:(NSNotification *)notification
{
1359 1360 1361 1362
    if (_preBackgroundWrapperView) {
        [self setVideoOutputView:_preBackgroundWrapperView];
        _preBackgroundWrapperView = nil;
    }
1363 1364

    if (_mediaPlayer.numberOfVideoTracks > 0) {
1365
        /* re-enable video decoding */
1366 1367
        _mediaPlayer.currentVideoTrackIndex = 1;
    }
1368 1369 1370 1371 1372 1373 1374 1375 1376

    if (_shouldResumePlaying) {
        _shouldResumePlaying = NO;
        [_listPlayer play];
    }
}

#pragma mark - helpers

1377 1378 1379 1380
- (NSDictionary *)mediaOptionsDictionary
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    return @{ kVLCSettingNetworkCaching : [defaults objectForKey:kVLCSettingNetworkCaching],
1381 1382 1383
              kVLCSettingStretchAudio : [[defaults objectForKey:kVLCSettingStretchAudio] boolValue] ? kVLCSettingStretchAudioOnValue : kVLCSettingStretchAudioOffValue,
              kVLCSettingTextEncoding : [defaults objectForKey:kVLCSettingTextEncoding],
              kVLCSettingSkipLoopFilter : [defaults objectForKey:kVLCSettingSkipLoopFilter],
Soomin Lee's avatar
Soomin Lee committed
1384
#if TARGET_OS_IOS
1385
              kVLCSettingHWDecoding : [defaults objectForKey:kVLCSettingHWDecoding]};
Soomin Lee's avatar
Soomin Lee committed
1386 1387 1388
#else
                };
#endif
1389 1390
}

1391
@end