VLCPlaybackController.m 40.5 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
141
142
143
- (void)openVideoSubTitlesFromFile:(NSString *)pathToFile
{
    [_mediaPlayer openVideoSubTitlesFromFile:pathToFile];
}

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
    if (_errorCallback && _mediaPlayer.state == VLCMediaPlayerStateError &&  !_sessionWillRestart)
298
299
300
        [[UIApplication sharedApplication] openURL:_errorCallback];
    else if (_successCallback && !_sessionWillRestart)
        [[UIApplication sharedApplication] openURL:_successCallback];
301

302
    [[self remoteControlService] unsubscribeFromRemoteCommands];
303

304
    [_playbackSessionManagementLock unlock];
305
306
307
    if (!_sessionWillRestart) {
        [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidStop object:self];
    } else {
308
        _sessionWillRestart = NO;
309
        [self startPlayback];
310
    }
311
312
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
313
#if TARGET_OS_IOS
314
315
- (void)_savePlaybackState
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
316
317
318
319
320
321
322
    @try {
        [[MLMediaLibrary sharedMediaLibrary] save];
    }
    @catch (NSException *exception) {
        APLog(@"saving playback state failed");
    }

323
    NSArray *files = [MLFile fileForURL:_mediaPlayer.media.url];
324
    MLFile *fileItem = files.firstObject;
325

326
327
    if (!fileItem) {
        APLog(@"couldn't find file, not saving playback progress");
328
        return;
329
    }
330
331
332
333
334
335
336
337
338
339

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

        if (position > .95)
            return;

340
341
342
343
344
345
346
347
348
349
350
351
352
        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];
            }
        }
353
354
355
356
357
    }
    @catch (NSException *exception) {
        APLog(@"failed to save current media state - file removed?");
    }
}
Felix Paul Kühne's avatar
Felix Paul Kühne committed
358
#endif
359

Felix Paul Kühne's avatar
Felix Paul Kühne committed
360
#if TARGET_OS_IOS
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
- (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];
393
}
Felix Paul Kühne's avatar
Felix Paul Kühne committed
394
#endif
395
396
397

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
398
399
    if (_mediaWasJustStarted) {
        _mediaWasJustStarted = NO;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
400
#if TARGET_OS_IOS
401
402
        if (self.mediaList) {
            NSArray *matches = [MLFile fileForURL:_mediaPlayer.media.url];
403
            MLFile *item = matches.firstObject;
404
405
            [self _recoverLastPlaybackStateOfItem:item];
        }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
406
407
408
#else
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        BOOL bValue = [defaults boolForKey:kVLCSettingUseSPDIF];
409

Felix Paul Kühne's avatar
Felix Paul Kühne committed
410
        if (bValue) {
411
           _mediaPlayer.audio.passthrough = bValue;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
412
        }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
413
#endif
414
415
    }

416
417
    if ([self.delegate respondsToSelector:@selector(playbackPositionUpdated:)])
        [self.delegate playbackPositionUpdated:self];
418
419
420

    [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackPositionUpdated
                                                        object:self];
421
422
423
424
}

- (NSInteger)mediaDuration
{
425
    return _mediaPlayer.media.length.intValue;;
426
427
428
429
430
431
432
}

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

433
434
435
436
437
- (BOOL)willPlay
{
    return _mediaPlayer.willPlay;
}

438
439
440
441
442
443
444
445
446
447
448
449
- (VLCRepeatMode)repeatMode
{
    return _listPlayer.repeatMode;
}

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

- (BOOL)currentMediaHasChapters
{
450
    return [_mediaPlayer numberOfTitles] > 1 || [_mediaPlayer numberOfChaptersForTitle:_mediaPlayer.currentTitleIndex] > 1;
451
452
453
454
455
456
457
}

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

458
459
460
461
462
- (BOOL) isSeekable
{
    return _mediaPlayer.isSeekable;
}

463
464
465
466
467
- (NSNumber *)playbackTime
{
    return _mediaPlayer.time.value;
}

468
469
- (float)playbackRate
{
470
    return _mediaPlayer.rate;
471
472
473
474
}

- (void)setPlaybackRate:(float)playbackRate
{
475
476
    [_mediaPlayer setRate:playbackRate];
    _metadata.playbackRate = @(_mediaPlayer.rate);
477
478
}

479
480
481
482
- (void)setAudioDelay:(float)audioDelay
{
    _mediaPlayer.currentAudioPlaybackDelay = 1000000.*audioDelay;
}
483

484
485
486
487
- (float)audioDelay
{
    return _mediaPlayer.currentAudioPlaybackDelay/1000000.;
}
488

489
490
491
492
493
494
495
496
497
498
499
- (float)playbackPosition
{
    return [_mediaPlayer position];
}

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

- (void)setSubtitleDelay:(float)subtitleDeleay
500
501
502
{
    _mediaPlayer.currentVideoSubTitleDelay = 1000000.*subtitleDeleay;
}
503

504
505
506
507
508
- (float)subtitleDelay
{
    return _mediaPlayer.currentVideoSubTitleDelay/1000000.;
}

509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
- (float)hue
{
    return _mediaPlayer.hue;
}

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

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

524
- (void)setContrast:(float)contrast
525
{
526
    _mediaPlayer.contrast = contrast;
527
528
529
530
531
532
}

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

534
535
536
537
- (void)setBrightness:(float)brightness
{
    _mediaPlayer.brightness = brightness;
}
538

539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
- (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.;
}

568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
- (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;
}

585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
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
- (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;
    }
}

685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
- (void)shortJumpForward
{
    [_mediaPlayer shortJumpForward];
}

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

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

700
701
702
703
704
- (void)setAudioPassthrough:(BOOL)shouldPass
{
    _mediaPlayer.audio.passthrough = shouldPass;
}

705
706
- (void)mediaPlayerStateChanged:(NSNotification *)aNotification
{
707
    VLCMediaPlayerState currentState = _mediaPlayer.state;
708

709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
    switch (currentState) {
        case VLCMediaPlayerStateBuffering: {
            /* attach delegate */
            _mediaPlayer.media.delegate = self;

            /* on-the-fly values through hidden API */
            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]];
        } break;

        case VLCMediaPlayerStateError: {
            APLog(@"Playback failed");
            dispatch_async(dispatch_get_main_queue(),^{
                [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidFail object:self];
            });
727
            _sessionWillRestart = NO;
728
            [self stopPlayback];
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
        } 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: {
            MLFile *item = [MLFile fileForURL:_mediaPlayer.media.url].firstObject;

            if (item) {
                _mediaPlayer.currentAudioTrackIndex = item.lastAudioTrack.intValue;
                _mediaPlayer.currentVideoSubTitleIndex = item.lastSubtitleTrack.intValue;
            }
        } break;
        default:
            break;
755
    }
756

757
    if ([self.delegate respondsToSelector:@selector(mediaPlayerStateChanged:isPlaying:currentMediaHasTrackToChooseFrom:currentMediaHasChapters:forPlaybackController:)])
758
        [self.delegate mediaPlayerStateChanged:currentState
759
760
761
762
                                     isPlaying:_mediaPlayer.isPlaying
              currentMediaHasTrackToChooseFrom:self.currentMediaHasTrackToChooseFrom
                       currentMediaHasChapters:self.currentMediaHasChapters
                         forPlaybackController:self];
763
764

    [self setNeedsMetadataUpdate];
765
766
767
768
769
}

#pragma mark - playback controls
- (void)playPause
{
770
771
772
773
774
775
776
777
778
779
780
781
    [_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
782
#if TARGET_OS_IOS
783
    [self _savePlaybackState];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
784
#endif
785
    [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
786
787
}

788
- (void)next
789
{
Soomin Lee's avatar
Soomin Lee committed
790
791
    NSInteger mediaListCount = _mediaList.count;

Soomin Lee's avatar
Soomin Lee committed
792
#if TARGET_OS_IOS
793
    if (self.repeatMode != VLCRepeatCurrentItem && mediaListCount > 2 && _shuffleMode) {
Soomin Lee's avatar
Soomin Lee committed
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814

        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
815
#endif
Soomin Lee's avatar
Soomin Lee committed
816
817

    if (mediaListCount > 1) {
818
        [_listPlayer next];
819
        [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
820
821
822
823
824
825
    } else {
        NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackForwardSkipLength];
        [_mediaPlayer jumpForward:skipLength.intValue];
    }
}

826
- (void)previous
827
{
828
    if (_mediaList.count > 1) {
829
        [_listPlayer previous];
830
        [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:self];
831
832
833
834
835
836
837
    }
    else {
        NSNumber *skipLength = [[NSUserDefaults standardUserDefaults] valueForKey:kVLCSettingPlaybackBackwardSkipLength];
        [_mediaPlayer jumpBackward:skipLength.intValue];
    }
}

838

839
840
841
842
843
844
845
846
847
848
- (void)jumpForward:(int)interval
{
    [_mediaPlayer jumpForward:interval];
}

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

849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
- (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];
}

865
866
- (void)switchAspectRatio
{
867
868
869
870
    _currentAspectRatio = _currentAspectRatio == VLCAspectRatioSixteenToTen ? VLCAspectRatioDefault : _currentAspectRatio + 1;
    switch (_currentAspectRatio) {
        case VLCAspectRatioDefault:
            _mediaPlayer.videoAspectRatio = NULL;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
871
            _mediaPlayer.videoCropGeometry = NULL;
872
873
874
875
876
877
878
879
880
            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];
881
    }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
882

883
884
885
886
    if ([self.delegate respondsToSelector:@selector(showStatusMessage:forPlaybackController:)]) {
        [self.delegate showStatusMessage:[NSString stringWithFormat:NSLocalizedString(@"AR_CHANGED", nil), [self stringForAspectRatio:_currentAspectRatio]] forPlaybackController:self];
    }
}
887

888
889
890
891
892
893
894
895
- (NSString *)stringForAspectRatio:(VLCAspectRatio)ratio
{
    switch (ratio) {
            case VLCAspectRatioFillToScreen:
            return NSLocalizedString(@"FILL_TO_SCREEN", nil);
            case VLCAspectRatioDefault:
            return NSLocalizedString(@"DEFAULT", nil);
            case VLCAspectRatioFourToThree:
896
            return @"4:3";
897
            case VLCAspectRatioSixteenToTen:
898
            return @"16:10";
899
            case VLCAspectRatioSixteenToNine:
900
            return @"16:9";
901
902
        default:
            NSAssert(NO, @"this shouldn't happen");
903
904
905
    }
}

906
907
908
909
910
911
912
913
914
915
916
917
918
919
- (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;
            }
        }
    }
}

920
921
922
- (void)setVideoOutputView:(UIView *)videoOutputView
{
    if (videoOutputView) {
923
924
925
        if ([_actualVideoOutputView superview] != nil)
            [_actualVideoOutputView removeFromSuperview];

926
927
        _actualVideoOutputView.frame = (CGRect){CGPointZero, videoOutputView.frame.size};

928
        [self setVideoTrackEnabled:true];
929

930
        [videoOutputView addSubview:_actualVideoOutputView];
931
932
933
        [_actualVideoOutputView layoutSubviews];
        [_actualVideoOutputView updateConstraints];
        [_actualVideoOutputView setNeedsLayout];
934
    } else
935
936
937
938
939
940
941
942
943
944
        [_actualVideoOutputView removeFromSuperview];

    _videoOutputViewWrapper = videoOutputView;
}

- (UIView *)videoOutputView
{
    return _videoOutputViewWrapper;
}

945
#pragma mark - 360 Support
Soomin Lee's avatar
Soomin Lee committed
946
#if !TARGET_OS_TV
947
948
949
950
951
952
953
954
955
956
957
958
959
- (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;

960
961
962
963
        for (NSDictionary *track in tracksInfo) {
            if ([track[VLCMediaTracksInformationType] isEqualToString:VLCMediaTracksInformationTypeVideo]) {
                return [track[VLCMediaTracksInformationVideoProjection] integerValue];
            }
964
965
966
967
        }
    }
    return -1;
}
Soomin Lee's avatar
Soomin Lee committed
968
#endif
969

970
971
972
973
974
975
976
977
978
979
980
981
982
983
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
#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];
}

1012
1013
1014
#pragma mark - AVAudioSession Notification Observers

- (void)handleInterruption:(NSNotification *)notification
1015
{
1016
1017
1018
1019
    NSDictionary *userInfo = notification.userInfo;

    if (!userInfo || !userInfo[AVAudioSessionInterruptionTypeKey]) {
        return;
1020
1021
    }

1022
1023
1024
1025
1026
1027
    NSUInteger interruptionType = [userInfo[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];

    if (interruptionType == AVAudioSessionInterruptionTypeBegan) {
        [_mediaPlayer pause];
    } else if (interruptionType == AVAudioSessionInterruptionTypeEnded
               && [userInfo[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue] == AVAudioSessionInterruptionOptionShouldResume) {
1028
1029
1030
1031
        [_mediaPlayer play];
    }
}

1032
- (BOOL)areHeadphonesPlugged
1033
1034
{
    NSArray *outputs = [[AVAudioSession sharedInstance] currentRoute].outputs;
1035
    NSString *portName = [[outputs firstObject] portName];
1036
1037
1038
1039
1040
    return [portName isEqualToString:@"Headphones"];
}

- (void)audioSessionRouteChange:(NSNotification *)notification
{
1041
1042
1043
1044
1045
1046
    NSDictionary *userInfo = notification.userInfo;
    NSInteger routeChangeReason = [[userInfo valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];

    if (routeChangeReason == AVAudioSessionRouteChangeReasonRouteConfigurationChange)
        return;

1047
    BOOL headphonesPlugged = [self areHeadphonesPlugged];
1048

1049
    if (_headphonesWasPlugged && !headphonesPlugged && [_mediaPlayer isPlaying]) {
1050
        [_mediaPlayer pause];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
1051
#if TARGET_OS_IOS
1052
        [self _savePlaybackState];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
1053
#endif
1054
1055
        [[NSNotificationCenter defaultCenter] postNotificationName:VLCPlaybackControllerPlaybackDidPause object:self];
    }
1056
    _headphonesWasPlugged = headphonesPlugged;
1057
1058
1059
1060
}

#pragma mark - Managing the media item

1061
1062
1063
- (VLCMedia *)currentlyPlayingMedia
{
    return _mediaPlayer.media;
1064
1065
1066
}

#pragma mark - metadata handling
1067
1068
1069
1070
- (void)performNavigationAction:(VLCMediaPlaybackNavigationAction)action
{
    [_mediaPlayer performNavigationAction:action];
}
1071
1072
- (void)mediaDidFinishParsing:(VLCMedia *)aMedia
{
1073
    [self setNeedsMetadataUpdate];
1074
1075
1076
1077
}

- (void)mediaMetaDataDidChange:(VLCMedia*)aMedia
{
1078
1079
1080
1081
1082
1083
1084
    [self setNeedsMetadataUpdate];
}

- (void)setNeedsMetadataUpdate
{
    if (_needsMetadataUpdate == NO) {
        _needsMetadataUpdate = YES;
1085
        dispatch_async(dispatch_get_main_queue(), ^{
1086
1087
1088
1089
            [_metadata updateMetadataFromMediaPlayer:_mediaPlayer];
            _needsMetadataUpdate = NO;
            if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:metadata:)])
                [self.delegate displayMetadataForPlaybackController:self metadata:_metadata];
1090
1091
        });
    }
1092
1093
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
1094
#if TARGET_OS_IOS
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
- (void)_recoverLastPlaybackStateOfItem:(MLFile *)item
{
    if (item) {
        CGFloat lastPosition = .0;
        NSInteger duration = 0;

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

1105
        if (lastPosition < .95 && _mediaPlayer.position < lastPosition) {
1106
            NSInteger continuePlayback;
1107
            if ([item isAlbumTrack] || [item isSupportedAudioFile])
1108
1109
1110
1111
                continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinueAudioPlayback] integerValue];
            else
                continuePlayback = [[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingContinuePlayback] integerValue];

1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
            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];
            }
        }
1128
1129
    }
}
Felix Paul Kühne's avatar
Felix Paul Kühne committed
1130
#endif
1131

1132
1133
- (void)recoverDisplayedMetadata
{
1134
1135
    if ([self.delegate respondsToSelector:@selector(displayMetadataForPlaybackController:metadata:)])
        [self.delegate displayMetadataForPlaybackController:self metadata:_metadata];
1136
1137
}

1138
1139
1140
1141
1142
1143
1144
1145
- (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];
1146
1147
    if ([self.delegate respondsToSelector:@selector(prepareForMediaPlayback:)])
        [self.delegate prepareForMediaPlayback:self];
1148
1149
}

1150
1151
1152
1153
1154
1155
1156
1157
1158
- (void)scheduleSleepTimerWithInterval:(NSTimeInterval)timeInterval
{
    if (_sleepTimer) {
        [_sleepTimer invalidate];
        _sleepTimer = nil;
    }
    _sleepTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(stopPlayback) userInfo:nil repeats:NO];
}

1159
1160
1161
1162
#pragma mark - background interaction

- (void)applicationWillResignActive:(NSNotification *)aNotification
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
1163
#if TARGET_OS_IOS
1164
    [self _savePlaybackState];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
1165
#endif
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176

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

- (void)applicationDidEnterBackground:(NSNotification *)notification
{
1177
1178
1179
    _preBackgroundWrapperView = _videoOutputViewWrapper;

    if (_mediaPlayer.audioTrackIndexes.count > 0)
1180
        [self setVideoTrackEnabled:false];
1181
1182
1183
1184
}

- (void)applicationDidBecomeActive:(NSNotification *)notification
{
1185
1186
1187
1188
    if (_preBackgroundWrapperView) {
        [self setVideoOutputView:_preBackgroundWrapperView];
        _preBackgroundWrapperView = nil;
    }
1189

1190
    [self setVideoTrackEnabled:true];
1191
1192
1193
1194
1195
1196

    if (_shouldResumePlaying) {
        _shouldResumePlaying = NO;
        [_listPlayer play];
    }
}
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
#pragma mark - remoteControlDelegate

- (void)remoteControlServiceHitPause:(VLCRemoteControlService *)rcs
{
    [_listPlayer pause];
}

- (void)remoteControlServiceHitPlay:(VLCRemoteControlService *)rcs
{
    [_listPlayer play];
}

- (void)remoteControlServiceTogglePlayPause:(VLCRemoteControlService *)rcs
{
    [self playPause];
}
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
- (void)remoteControlServiceHitStop:(VLCRemoteControlService *)rcs
{
    //TODO handle stop playback entirely
    [_listPlayer stop];
}

- (BOOL)remoteControlServiceHitPlayNextIfPossible:(VLCRemoteControlService *)rcs
{
    //TODO This doesn't handle shuffle or repeat yet
    return [_listPlayer next];
}

- (BOOL)remoteControlServiceHitPlayPreviousIfPossible:(VLCRemoteControlService *)rcs
{
    //TODO This doesn't handle shuffle or repeat yet
    return [_listPlayer previous];
}

- (void)remoteControlService:(VLCRemoteControlService *)rcs jumpForwardInSeconds:(NSTimeInterval)seconds
{
    [_mediaPlayer jumpForward:seconds];
}

- (void)remoteControlService:(VLCRemoteControlService *)rcs jumpBackwardInSeconds:(NSTimeInterval)seconds
{
    [_mediaPlayer jumpBackward:seconds];
}

- (NSInteger)remoteControlServiceNumberOfMediaItemsinList:(VLCRemoteControlService *)rcs
{
    return _mediaList.count;
}

- (void)remoteControlService:(VLCRemoteControlService *)rcs setPlaybackRate:(CGFloat)playbackRate
{
    self.playbackRate = playbackRate;
}
1251
1252
#pragma mark - helpers

1253
1254
1255
1256
- (NSDictionary *)mediaOptionsDictionary
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    return @{ kVLCSettingNetworkCaching : [defaults objectForKey:kVLCSettingNetworkCaching],
1257
1258
1259
              kVLCSettingStretchAudio : [[defaults objectForKey:kVLCSettingStretchAudio] boolValue] ? kVLCSettingStretchAudioOnValue : kVLCSettingStretchAudioOffValue,
              kVLCSettingTextEncoding : [defaults objectForKey:kVLCSettingTextEncoding],
              kVLCSettingSkipLoopFilter : [defaults objectForKey:kVLCSettingSkipLoopFilter],
1260
              kVLCSettingHardwareDecoding : [defaults objectForKey:kVLCSettingHardwareDecoding]};
1261
1262
}

1263
@end