VLCPlaybackController.m 41.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*****************************************************************************
 * 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 "UIDevice+VLC.h"
#import <AVFoundation/AVFoundation.h>
22
#import "VLCPlayerDisplayController.h"
23
#import "VLCConstants.h"
24
#import "VLCRemoteControlService.h"
25
#import "VLCMetadata.h"
26

27 28 29 30 31 32
NSString *const VLCPlaybackControllerPlaybackDidStart = @"VLCPlaybackControllerPlaybackDidStart";
NSString *const VLCPlaybackControllerPlaybackDidPause = @"VLCPlaybackControllerPlaybackDidPause";
NSString *const VLCPlaybackControllerPlaybackDidResume = @"VLCPlaybackControllerPlaybackDidResume";
NSString *const VLCPlaybackControllerPlaybackDidStop = @"VLCPlaybackControllerPlaybackDidStop";
NSString *const VLCPlaybackControllerPlaybackMetadataDidChange = @"VLCPlaybackControllerPlaybackMetadataDidChange";
NSString *const VLCPlaybackControllerPlaybackDidFail = @"VLCPlaybackControllerPlaybackDidFail";
33
NSString *const VLCPlaybackControllerPlaybackPositionUpdated = @"VLCPlaybackControllerPlaybackPositionUpdated";
34

35 36 37 38 39 40 41 42
typedef NS_ENUM(NSUInteger, VLCAspectRatio) {
    VLCAspectRatioDefault = 0,
    VLCAspectRatioFillToScreen,
    VLCAspectRatioFourToThree,
    VLCAspectRatioSixteenToNine,
    VLCAspectRatioSixteenToTen,
};

43
@interface VLCPlaybackController () <VLCMediaPlayerDelegate, VLCMediaDelegate, VLCRemoteControlServiceDelegate>
44
{
45
    VLCRemoteControlService *_remoteControlService;
46
    VLCMediaPlayer *_mediaPlayer;
47
    VLCMediaListPlayer *_listPlayer;
48 49
    BOOL _playerIsSetup;
    BOOL _shouldResumePlaying;
50 51 52 53
    BOOL _sessionWillRestart;

    NSString *_pathToExternalSubtitlesFile;
    int _itemInMediaListToBePlayedFirst;
54
    NSTimer *_sleepTimer;
55

56
    NSUInteger _currentAspectRatio;
57 58 59

    UIView *_videoOutputViewWrapper;
    UIView *_actualVideoOutputView;
60
    UIView *_preBackgroundWrapperView;
61

62
    BOOL _needsMetadataUpdate;
63
    BOOL _mediaWasJustStarted;
64
    BOOL _recheckForExistingThumbnail;
65
    BOOL _headphonesWasPlugged;
66 67

    NSLock *_playbackSessionManagementLock;
68 69

    VLCDialogProvider *_dialogProvider;
Soomin Lee's avatar
Soomin Lee committed
70 71

    NSMutableArray *_shuffleStack;
72 73 74 75 76 77 78 79 80 81 82 83 84 85
}

@end

@implementation VLCPlaybackController

#pragma mark instance management

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

    dispatch_once(&pred, ^{
86
        sharedInstance = [VLCPlaybackController new];
87 88 89 90 91 92 93
    });

    return sharedInstance;
}

- (void)dealloc
{
94
    _dialogProvider = nil;
95 96 97
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

Tobias's avatar
Tobias committed
98 99 100 101
- (instancetype)init
{
    self = [super init];
    if (self) {
102
        // listen to audiosessions and appkit callback
103
        _headphonesWasPlugged = [self areHeadphonesPlugged];
Tobias's avatar
Tobias committed
104 105 106
        NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
        [defaultCenter addObserver:self selector:@selector(audioSessionRouteChange:)
                              name:AVAudioSessionRouteChangeNotification object:nil];
107

108 109 110
        [defaultCenter addObserver:self selector:@selector(handleInterruption:)
                              name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];

111
        // appkit because we neeed to know when we go to background in order to stop the video, so that we don't crash
Tobias's avatar
Tobias committed
112 113 114 115 116 117
        [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];
118

119
        _metadata = [VLCMetaData new];
120 121
        _dialogProvider = [[VLCDialogProvider alloc] initWithLibrary:[VLCLibrary sharedLibrary] customUI:NO];

122
        _playbackSessionManagementLock = [[NSLock alloc] init];
Soomin Lee's avatar
Soomin Lee committed
123 124
        _shuffleMode = NO;
        _shuffleStack = [[NSMutableArray alloc] init];
Tobias's avatar
Tobias committed
125 126 127 128
    }
    return self;
}

129 130 131 132 133 134 135 136
- (VLCRemoteControlService *)remoteControlService
{
    if (!_remoteControlService) {
        _remoteControlService = [[VLCRemoteControlService alloc] init];
        _remoteControlService.remoteControlServiceDelegate = self;
    }
    return _remoteControlService;
}
137 138
#pragma mark - playback management

139 140
- (void)openVideoSubTitlesFromFile:(NSString *)pathToFile
{
141
    [_mediaPlayer addPlaybackSlave:[NSURL fileURLWithPath:pathToFile] type:VLCMediaPlaybackSlaveTypeSubtitle enforce:YES];
142 143
}

144
- (void)playMediaList:(VLCMediaList *)mediaList firstIndex:(NSInteger)index subtitlesFilePath:(NSString *)subsFilePath
145 146
{
    self.mediaList = mediaList;
147 148
    _itemInMediaListToBePlayedFirst = (int)index;
    _pathToExternalSubtitlesFile = subsFilePath;
149

150 151
    _sessionWillRestart = _playerIsSetup;
    _playerIsSetup ? [self stopPlayback] : [self startPlayback];
152 153
}

154 155 156 157 158
- (VLCTime *)playedTime
{
    return [_mediaPlayer time];
}

159 160
- (void)startPlayback
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
161 162
    if (_playerIsSetup) {
        APLog(@"%s: player is already setup, bailing out", __PRETTY_FUNCTION__);
163
        return;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
164
    }
165 166 167 168 169 170 171

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

172 173
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

174
    if (!self.mediaList) {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
175
        APLog(@"%s: no URL and no media list set, stopping playback", __PRETTY_FUNCTION__);
176
        [_playbackSessionManagementLock unlock];
177 178 179
        [self stopPlayback];
        return;
    }
180

181 182 183 184 185 186 187
    /* 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;

188 189
    if (_pathToExternalSubtitlesFile)
        _listPlayer = [[VLCMediaListPlayer alloc] initWithOptions:@[[NSString stringWithFormat:@"--%@=%@", kVLCSettingSubtitlesFilePath, _pathToExternalSubtitlesFile]] andDrawable:_actualVideoOutputView];
190 191 192 193 194 195 196 197
    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;

198 199 200 201 202 203 204 205
    _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];
206 207
    if (_pathToExternalSubtitlesFile)
        [_mediaPlayer addPlaybackSlave:[NSURL fileURLWithPath:_pathToExternalSubtitlesFile] type:VLCMediaPlaybackSlaveTypeSubtitle enforce:YES];
208

209 210 211 212 213 214
    VLCMedia *media = [_mediaList mediaAtIndex:_itemInMediaListToBePlayedFirst];
    [media parseWithOptions:VLCMediaParseLocal];
    media.delegate = self;
    [media addOptions:self.mediaOptionsDictionary];

    [_listPlayer setMediaList:self.mediaList];
215

216 217
    [_listPlayer setRepeatMode:VLCDoNotRepeat];

218 219
    [_playbackSessionManagementLock unlock];

220
    [self _playNewMedia];
221 222 223 224
}

- (void)_playNewMedia
{
225 226
    BOOL ret = [_playbackSessionManagementLock tryLock];
    if (!ret) {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
227
        APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
228 229 230
        return;
    }

231 232 233 234 235
    // Set last selected equalizer profile
    unsigned int profile = (unsigned int)[[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingEqualizerProfile] integerValue];
    [_mediaPlayer resetEqualizerFromProfile:profile];
    [_mediaPlayer setPreAmplification:[_mediaPlayer preAmplification]];

236 237
    _mediaWasJustStarted = YES;

238 239 240
    [_mediaPlayer addObserver:self forKeyPath:@"time" options:0 context:nil];
    [_mediaPlayer addObserver:self forKeyPath:@"remainingTime" options:0 context:nil];

241
    [_listPlayer playItemAtNumber:@(_itemInMediaListToBePlayedFirst)];
242 243 244 245

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

246
    _currentAspectRatio = VLCAspectRatioDefault;
247
    _mediaPlayer.videoAspectRatio = NULL;
248
    _mediaPlayer.videoCropGeometry = NULL;
249

250
    [[self remoteControlService] subscribeToRemoteCommands];
251

252
    _playerIsSetup = YES;
253

254
    [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidStart object:self];
255
    [_playbackSessionManagementLock unlock];
256 257 258 259
}

- (void)stopPlayback
{
260 261 262 263 264 265
    BOOL ret = [_playbackSessionManagementLock tryLock];
    if (!ret) {
        APLog(@"%s: locking failed", __PRETTY_FUNCTION__);
        return;
    }

266 267 268 269 270 271 272 273 274 275 276
    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
277
#if TARGET_OS_IOS
278
            [self _savePlaybackState];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
279
#endif
280 281
            [_mediaPlayer stop];
        }
282 283
        _mediaPlayer = nil;
        _listPlayer = nil;
284
    }
285
    if (!_sessionWillRestart) {
286
        _mediaList = nil;
287 288 289 290 291 292
        if (_pathToExternalSubtitlesFile) {
            NSFileManager *fileManager = [NSFileManager defaultManager];
            if ([fileManager fileExistsAtPath:_pathToExternalSubtitlesFile])
                [fileManager removeItemAtPath:_pathToExternalSubtitlesFile error:nil];
            _pathToExternalSubtitlesFile = nil;
        }
293 294
    }
    _playerIsSetup = NO;
Soomin Lee's avatar
Soomin Lee committed
295
    [_shuffleStack removeAllObjects];
296

297 298 299
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    /* UIApplication's replacement calls require iOS 10 or later, which we can't enforce as of yet */
300
    if (_errorCallback && _mediaPlayer.state == VLCMediaPlayerStateError &&  !_sessionWillRestart)
301
        [[UIApplication sharedApplication] openURL:_errorCallback];
302
    else if (_successCallback && !_sessionWillRestart)
303
        [[UIApplication sharedApplication] openURL:_successCallback];
304
#pragma clang diagnostic pop
305

306
    [[self remoteControlService] unsubscribeFromRemoteCommands];
307

308
    [_playbackSessionManagementLock unlock];
309 310 311
    if (!_sessionWillRestart) {
        [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidStop object:self];
    } else {
312
        _sessionWillRestart = NO;
313
        [self startPlayback];
314
    }
315 316
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
317
#if TARGET_OS_IOS
318 319 320 321 322 323 324 325 326 327 328

- (void)restoreAudioAndSubtitleTrack
{
    MLFile *item = [MLFile fileForURL:_mediaPlayer.media.url].firstObject;

    if (item) {
        _mediaPlayer.currentAudioTrackIndex = item.lastAudioTrack.intValue;
        _mediaPlayer.currentVideoSubTitleIndex = item.lastSubtitleTrack.intValue;
    }
}

329 330
- (void)_savePlaybackState
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
331 332 333 334 335 336 337
    @try {
        [[MLMediaLibrary sharedMediaLibrary] save];
    }
    @catch (NSException *exception) {
        APLog(@"saving playback state failed");
    }

338
    NSArray *files = [MLFile fileForURL:_mediaPlayer.media.url];
339
    MLFile *fileItem = files.firstObject;
340

341 342
    if (!fileItem) {
        APLog(@"couldn't find file, not saving playback progress");
343
        return;
344
    }
345 346 347 348 349 350 351 352 353 354

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

        if (position > .95)
            return;

355 356 357 358 359 360 361 362 363 364 365 366 367
        if (_mediaPlayer.hasVideoOut) {
            NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
            NSString *newThumbnailPath = [searchPaths.firstObject stringByAppendingPathComponent:@"VideoSnapshots"];
            NSError *error;

            [[NSFileManager defaultManager] createDirectoryAtPath:newThumbnailPath withIntermediateDirectories:YES attributes:nil error:&error];
            if (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];
            }
        }
368 369 370 371 372
    }
    @catch (NSException *exception) {
        APLog(@"failed to save current media state - file removed?");
    }
}
Felix Paul Kühne's avatar
Felix Paul Kühne committed
373
#endif
374

Felix Paul Kühne's avatar
Felix Paul Kühne committed
375
#if TARGET_OS_IOS
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
- (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];
408
}
Felix Paul Kühne's avatar
Felix Paul Kühne committed
409
#endif
410 411 412

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
413 414
    if (_mediaWasJustStarted) {
        _mediaWasJustStarted = NO;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
415
#if TARGET_OS_IOS
416 417
        if (self.mediaList) {
            NSArray *matches = [MLFile fileForURL:_mediaPlayer.media.url];
418
            MLFile *item = matches.firstObject;
419 420
            [self _recoverLastPlaybackStateOfItem:item];
        }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
421 422 423
#else
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        BOOL bValue = [defaults boolForKey:kVLCSettingUseSPDIF];
424

Felix Paul Kühne's avatar
Felix Paul Kühne committed
425
        if (bValue) {
426
           _mediaPlayer.audio.passthrough = bValue;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
427
        }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
428
#endif
429 430
    }

431 432
    if ([self.delegate respondsToSelector:@selector(playbackPositionUpdated:)])
        [self.delegate playbackPositionUpdated:self];
433 434 435

    [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackPositionUpdated
                                                        object:self];
436 437 438 439
}

- (NSInteger)mediaDuration
{
440
    return _mediaPlayer.media.length.intValue;;
441 442 443 444 445 446 447
}

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

448 449 450 451 452
- (BOOL)willPlay
{
    return _mediaPlayer.willPlay;
}

453 454 455 456 457 458 459 460 461 462 463 464
- (VLCRepeatMode)repeatMode
{
    return _listPlayer.repeatMode;
}

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

- (BOOL)currentMediaHasChapters
{
465
    return [_mediaPlayer numberOfTitles] > 1 || [_mediaPlayer numberOfChaptersForTitle:_mediaPlayer.currentTitleIndex] > 1;
466 467 468 469 470 471 472
}

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

473 474 475 476 477
- (BOOL) isSeekable
{
    return _mediaPlayer.isSeekable;
}

478 479 480 481 482
- (NSNumber *)playbackTime
{
    return _mediaPlayer.time.value;
}

483 484
- (float)playbackRate
{
485
    return _mediaPlayer.rate;
486 487 488 489
}

- (void)setPlaybackRate:(float)playbackRate
{
490 491
    [_mediaPlayer setRate:playbackRate];
    _metadata.playbackRate = @(_mediaPlayer.rate);
492 493
}

494 495 496 497
- (void)setAudioDelay:(float)audioDelay
{
    _mediaPlayer.currentAudioPlaybackDelay = 1000000.*audioDelay;
}
498

499 500 501 502
- (float)audioDelay
{
    return _mediaPlayer.currentAudioPlaybackDelay/1000000.;
}
503

504 505 506 507 508 509 510 511 512 513 514
- (float)playbackPosition
{
    return [_mediaPlayer position];
}

- (void)setPlaybackPosition:(float)position
{
    _mediaPlayer.position = position;
}

- (void)setSubtitleDelay:(float)subtitleDeleay
515 516 517
{
    _mediaPlayer.currentVideoSubTitleDelay = 1000000.*subtitleDeleay;
}
518

519 520 521 522 523
- (float)subtitleDelay
{
    return _mediaPlayer.currentVideoSubTitleDelay/1000000.;
}

524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
- (float)hue
{
    return _mediaPlayer.hue;
}

- (void)setHue:(float)hue
{
    _mediaPlayer.hue = hue;
}

- (float)contrast
{
    return _mediaPlayer.contrast;
}

539
- (void)setContrast:(float)contrast
540
{
541
    _mediaPlayer.contrast = contrast;
542 543 544 545 546 547
}

- (float)brightness
{
    return _mediaPlayer.brightness;
}
548

549 550 551 552
- (void)setBrightness:(float)brightness
{
    _mediaPlayer.brightness = brightness;
}
553

554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
- (float)saturation
{
    return _mediaPlayer.saturation;
}

- (void)setSaturation:(float)saturation
{
    _mediaPlayer.saturation = saturation;
}

- (void)setGamma:(float)gamma
{
    _mediaPlayer.gamma = gamma;
}

- (float)gamma
{
    return _mediaPlayer.gamma;
}

- (void)resetFilters
{
    _mediaPlayer.hue = 0.;
    _mediaPlayer.contrast = 1.;
    _mediaPlayer.brightness = 1.;
    _mediaPlayer.saturation = 1.;
    _mediaPlayer.gamma = 1.;
}

583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
- (void)toggleRepeatMode
{
    VLCRepeatMode nextRepeatMode = VLCDoNotRepeat;
    switch (_listPlayer.repeatMode) {
        case VLCDoNotRepeat:
            nextRepeatMode = VLCRepeatCurrentItem;
            break;
        case VLCRepeatCurrentItem:
            nextRepeatMode = VLCRepeatAllItems;
            break;
        default:
            nextRepeatMode = VLCDoNotRepeat;
            break;
    }
    _listPlayer.repeatMode = nextRepeatMode;
}

600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
- (NSInteger)indexOfCurrentAudioTrack
{
    return [_mediaPlayer.audioTrackIndexes indexOfObject:@(_mediaPlayer.currentAudioTrackIndex)];
}

- (NSInteger)indexOfCurrentSubtitleTrack
{
    return [_mediaPlayer.videoSubTitlesIndexes indexOfObject:@(_mediaPlayer.currentVideoSubTitleIndex)];
}

- (NSInteger)indexOfCurrentChapter
{
    return _mediaPlayer.currentChapterIndex;
}

- (NSInteger)indexOfCurrentTitle
{
    return _mediaPlayer.currentTitleIndex;
}

- (NSInteger)numberOfAudioTracks
{
    return _mediaPlayer.audioTrackIndexes.count;
}

- (NSInteger)numberOfVideoSubtitlesIndexes
{
    return _mediaPlayer.videoSubTitlesIndexes.count;
}

- (NSInteger)numberOfTitles
{
    return  [_mediaPlayer numberOfTitles];
}

- (NSInteger)numberOfChaptersForCurrentTitle
{
    return [_mediaPlayer numberOfChaptersForTitle:_mediaPlayer.currentTitleIndex];
}

- (NSString *)videoSubtitleNameAtIndex:(NSInteger)index
{
    if (index >= 0 && index < _mediaPlayer.videoSubTitlesNames.count)
        return _mediaPlayer.videoSubTitlesNames[index];
    return nil;
}

- (NSString *)audioTrackNameAtIndex:(NSInteger)index
{
    if (index >= 0 && index < _mediaPlayer.audioTrackNames.count)
        return _mediaPlayer.audioTrackNames[index];
    return nil;
}

- (NSDictionary *)titleDescriptionsDictAtIndex:(NSInteger)index
{
    if (index >= 0 && index < _mediaPlayer.titleDescriptions.count)
        return _mediaPlayer.titleDescriptions[index];
    return nil;
}

- (NSDictionary *)chapterDescriptionsDictAtIndex:(NSInteger)index
{
    NSArray *chapterDescriptions = [_mediaPlayer chapterDescriptionsOfTitle:_mediaPlayer.currentTitleIndex];
    if (index >= 0 && index < chapterDescriptions.count)
        return chapterDescriptions[index];
    return nil;
}

- (void)selectAudioTrackAtIndex:(NSInteger)index
{
    if (index >= 0 && index < _mediaPlayer.audioTrackIndexes.count) {
        //we can cast this cause we won't have more than 2 million audiotracks
        _mediaPlayer.currentAudioTrackIndex = [_mediaPlayer.audioTrackIndexes[index] intValue];
    }
}

- (void)selectVideoSubtitleAtIndex:(NSInteger)index
{
    if (index >= 0 && index < _mediaPlayer.videoSubTitlesIndexes.count) {
        _mediaPlayer.currentVideoSubTitleIndex = [_mediaPlayer.videoSubTitlesIndexes[index] intValue];
    }
}

- (void)selectTitleAtIndex:(NSInteger)index
{
    if (index >= 0 && index < [_mediaPlayer numberOfTitles]) {
        //we can cast this cause we won't have more than 2 million titles
        _mediaPlayer.currentTitleIndex = (int)index;
    }
}

- (void)selectChapterAtIndex:(NSInteger)index
{
    if (index >= 0 && index < [self numberOfChaptersForCurrentTitle]) {
        //we can cast this cause we won't have more than 2 million chapters
        _mediaPlayer.currentChapterIndex = (int)index;
    }
}

700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
- (void)shortJumpForward
{
    [_mediaPlayer shortJumpForward];
}

- (void)shortJumpBackward
{
    [_mediaPlayer shortJumpBackward];
}

- (VLCTime *)remainingTime
{
    return [_mediaPlayer remainingTime];
}

715 716 717 718 719
- (void)setAudioPassthrough:(BOOL)shouldPass
{
    _mediaPlayer.audio.passthrough = shouldPass;
}

720 721
- (void)mediaPlayerStateChanged:(NSNotification *)aNotification
{
722
    VLCMediaPlayerState currentState = _mediaPlayer.state;
723

724 725 726 727 728 729 730
    switch (currentState) {
        case VLCMediaPlayerStateBuffering: {
            /* attach delegate */
            _mediaPlayer.media.delegate = self;

            /* on-the-fly values through hidden API */
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
731 732
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
733 734 735 736
            [_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]];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
737
#pragma clang diagnostic pop
738 739 740 741 742 743 744
        } break;

        case VLCMediaPlayerStateError: {
            APLog(@"Playback failed");
            dispatch_async(dispatch_get_main_queue(),^{
                [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidFail object:self];
            });
745
            _sessionWillRestart = NO;
746
            [self stopPlayback];
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
        } break;
        case VLCMediaPlayerStateEnded:
        case VLCMediaPlayerStateStopped: {
            [_listPlayer.mediaList lock];
            NSUInteger listCount = _listPlayer.mediaList.count;
            if ([_listPlayer.mediaList indexOfMedia:_mediaPlayer.media] == listCount - 1 && self.repeatMode == VLCDoNotRepeat) {
                [_listPlayer.mediaList unlock];
                _sessionWillRestart = NO;
                [self stopPlayback];
                return;
            } else if (listCount > 1) {
                [_listPlayer.mediaList unlock];
                [_listPlayer next];
            } else
                [_listPlayer.mediaList unlock];
        } break;
        case VLCMediaPlayerStateESAdded: {
764 765 766
#if TARGET_OS_IOS
            [self restoreAudioAndSubtitleTrack];
#endif
767 768 769
        } break;
        default:
            break;
770
    }
771

772
    if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
773
        [self.delegate mediaPlayerStateChanged:currentState
774 775 776 777
                                     isPlaying:_mediaPlayer.isPlaying
              currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
                       currentMediaHasChapters:self.currentMediaHasChapters
                         forPlaybackController:self];
778 779

    [self setNeedsMetadataUpdate];
780 781 782 783 784
}

#pragma mark - playback controls
- (void)playPause
{
785 786 787 788 789 790 791 792 793 794 795 796
    [_mediaPlayer isPlaying] ? [self pause] : [self play];
}

- (void)play
{
    [_listPlayer play];
    [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidResume object:self];
}

- (void)pause
{
    [_listPlayer pause];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
797
#if TARGET_OS_IOS
798
    [self _savePlaybackState];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
799
#endif
800
    [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
801 802
}

803
- (void)next
804
{
Soomin Lee's avatar
Soomin Lee committed
805 806
    NSInteger mediaListCount = _mediaList.count;

Soomin Lee's avatar
Soomin Lee committed
807
#if TARGET_OS_IOS
808
    if (self.repeatMode != VLCRepeatCurrentItem && mediaListCount > 2 && _shuffleMode) {
Soomin Lee's avatar
Soomin Lee committed
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829

        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
830
#endif
Soomin Lee's avatar
Soomin Lee committed
831 832

    if (mediaListCount > 1) {
833
        [_listPlayer next];
834
        [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
835 836 837 838 839 840
    } else {
        NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackForwardSkipLength];
        [_mediaPlayer jumpForward:skipLength.intValue];
    }
}

841
- (void)previous
842
{
843
    if (_mediaList.count > 1) {
844
        [_listPlayer previous];
845
        [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
846 847 848 849 850 851 852
    }
    else {
        NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackBackwardSkipLength];
        [_mediaPlayer jumpBackward:skipLength.intValue];
    }
}

853

854 855 856 857 858 859 860 861 862 863
- (void)jumpForward:(int)interval
{
    [_mediaPlayer jumpForward:interval];
}

- (void)jumpBackward:(int)interval
{
    [_mediaPlayer jumpBackward:interval];
}

864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
- (NSString *)screenAspectRatio
{
    UIScreen *screen = [[UIDevice currentDevice] VLCHasExternalDisplay] ? [UIScreen screens][1] : [UIScreen mainScreen];
    return [NSString stringWithFormat:@"%d:%d", (int)screen.bounds.size.width, (int)screen.bounds.size.height];
}

- (void)switchIPhoneXFullScreen
{
    BOOL inFullScreen = _mediaPlayer.videoCropGeometry && [[NSString stringWithUTF8String:_mediaPlayer.videoCropGeometry] isEqualToString:[self screenAspectRatio]];
    if (inFullScreen) {
        const char *previousAspectRatio = _currentAspectRatio == VLCAspectRatioDefault ? NULL : [[self stringForAspectRatio:_currentAspectRatio] UTF8String];
        _mediaPlayer.videoAspectRatio = (char *)previousAspectRatio;
    }
    _mediaPlayer.videoCropGeometry = inFullScreen ? NULL : (char *)[[self screenAspectRatio] UTF8String];
}

880 881
- (void)switchAspectRatio
{
882 883 884 885
    _currentAspectRatio = _currentAspectRatio == VLCAspectRatioSixteenToTen ? VLCAspectRatioDefault : _currentAspectRatio + 1;
    switch (_currentAspectRatio) {
        case VLCAspectRatioDefault:
            _mediaPlayer.videoAspectRatio = NULL;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
886
            _mediaPlayer.videoCropGeometry = NULL;
887 888 889 890 891 892 893 894 895
            break;
        case VLCAspectRatioFillToScreen:
            _mediaPlayer.videoCropGeometry = (char *)[[self screenAspectRatio] UTF8String];
            break;
        case VLCAspectRatioFourToThree:
        case VLCAspectRatioSixteenToTen:
        case VLCAspectRatioSixteenToNine:
            _mediaPlayer.videoCropGeometry = NULL;
            _mediaPlayer.videoAspectRatio = (char *)[[self stringForAspectRatio:_currentAspectRatio] UTF8String];
896
    }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
897

898 899 900 901
    if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)]) {
        [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), [self stringForAspectRatio:_currentAspectRatio]] forPlaybackController:self];
    }
}
902

903 904 905 906 907 908 909 910
- (NSString *)stringForAspectRatio:(VLCAspectRatio)ratio
{
    switch (ratio) {
            case VLCAspectRatioFillToScreen:
            return NSLocalizedString(@"FILL_TO_SCREEN", nil);
            case VLCAspectRatioDefault:
            return NSLocalizedString(@"DEFAULT", nil);
            case VLCAspectRatioFourToThree:
911
            return @"4:3";
912
            case VLCAspectRatioSixteenToTen:
913
            return @"16:10";
914
            case VLCAspectRatioSixteenToNine:
915
            return @"16:9";
916 917
        default:
            NSAssert(NO, @"this shouldn't happen");
918 919 920
    }
}

921 922 923 924 925 926 927 928 929 930 931 932 933 934
- (void)setVideoTrackEnabled:(BOOL)enabled
{
    if (!enabled)
        _mediaPlayer.currentVideoTrackIndex = -1;
    else if (_mediaPlayer.currentVideoTrackIndex == -1) {
        for (NSNumber *trackId in _mediaPlayer.videoTrackIndexes) {
            if ([trackId intValue] != -1) {
                _mediaPlayer.currentVideoTrackIndex = [trackId intValue];
                break;
            }
        }
    }
}

935 936 937
- (void)setVideoOutputView:(UIView *)videoOutputView
{
    if (videoOutputView) {
938 939 940
        if ([_actualVideoOutputView superview] != nil)
            [_actualVideoOutputView removeFromSuperview];

941 942
        _actualVideoOutputView.frame = (CGRect){CGPointZero, videoOutputView.frame.size};

943
        [self setVideoTrackEnabled:true];
944

945
        [videoOutputView addSubview:_actualVideoOutputView];
946 947 948
        [_actualVideoOutputView layoutSubviews];
        [_actualVideoOutputView updateConstraints];
        [_actualVideoOutputView setNeedsLayout];
949
    } else
950 951 952 953 954 955 956 957 958 959
        [_actualVideoOutputView removeFromSuperview];

    _videoOutputViewWrapper = videoOutputView;
}

- (UIView *)videoOutputView
{
    return _videoOutputViewWrapper;
}

960
#pragma mark - 360 Support
Soomin Lee's avatar
Soomin Lee committed
961
#if !TARGET_OS_TV
962 963 964 965 966 967 968 969 970 971 972 973 974
- (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;

975 976 977 978
        for (NSDictionary *track in tracksInfo) {
            if ([track[VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
                return [track[VLCMediaTracksInformationVideoProjection] integerValue];
            }
979 980 981 982
        }
    }
    return -1;
}
Soomin Lee's avatar
Soomin Lee committed
983
#endif
984

985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
#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];
}

1027 1028 1029
#pragma mark - AVAudioSession Notification Observers

- (void)handleInterruption:(NSNotification *)notification
1030
{
1031 1032 1033 1034
    NSDictionary *userInfo = notification.userInfo;

    if (!userInfo || !userInfo[AVAudioSessionInterruptionTypeKey]) {
        return;
1035 1036
    }

1037 1038 1039 1040 1041 1042
    NSUInteger interruptionType = [userInfo[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];

    if (interruptionType == AVAudioSessionInterruptionTypeBegan) {
        [_mediaPlayer pause];
    } else if (interruptionType == AVAudioSessionInterruptionTypeEnded
               && [userInfo[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue] == AVAudioSessionInterruptionOptionShouldResume) {
1043 1044 1045 1046
        [_mediaPlayer play];
    }
}

1047
- (BOOL)areHeadphonesPlugged
1048 1049
{
    NSArray *outputs = [[AVAudioSession sharedInstance] currentRoute].outputs;
1050
    NSString *portName = [[outputs firstObject] portName];
1051 1052 1053 1054 1055
    return [portName isEqualToString:@"Headphones"];
}

- (void)audioSessionRouteChange:(NSNotification *)notification
{
1056 1057 1058 1059 1060 1061
    NSDictionary *userInfo = notification.userInfo;
    NSInteger routeChangeReason = [[userInfo valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];

    if (routeChangeReason == AVAudioSessionRouteChangeReasonRouteConfigurationChange)
        return;

1062
    BOOL headphonesPlugged = [self areHeadphonesPlugged];
1063

1064
    if (_headphonesWasPlugged && !headphonesPlugged && [_mediaPlayer isPlaying]) {
1065
        [_mediaPlayer pause];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
1066
#if TARGET_OS_IOS
1067
        [self _savePlaybackState];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
1068
#endif
1069 1070
        [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
    }
1071
    _headphonesWasPlugged = headphonesPlugged;
1072 1073 1074 1075
}

#pragma mark - Managing the media item

1076 1077 1078
- (VLCMedia *)currentlyPlayingMedia
{
    return _mediaPlayer.media;