VLCMovieViewController.m 59.3 KB
Newer Older
1 2 3 4
/*****************************************************************************
 * VLCMovieViewController.m
 * VLC for iOS
 *****************************************************************************
5
 * Copyright (c) 2013-2015 VideoLAN. All rights reserved.
6 7 8 9
 * $Id$
 *
 * Authors: Felix Paul Kühne <fkuehne # videolan.org>
 *          Gleb Pinigin <gpinigin # gmail.com>
10 11
 *          Carola Nitz <caro # videolan.org>
 *          Tobias Conradi <videolan # tobias-conradi.de>
12 13 14
 *          Ahmad Harb <harb.dev.leb # gmail.com>
 *          Fabio Ritrovato <sephiroth87 # videolan.org>
 *          Pierre SAGASPE <pierre.sagaspe # me.com>
15 16 17 18
 *          Filipe Cabecinhas <vlc # filcab dot net>
 *          Marc Etcheverry <marc # taplightsoftware dot com>
 *          Christopher Loessl <cloessl # x-berg dot de>
 *          Sylver Bruneau <sylver.bruneau # gmail dot com>
19 20 21
 *
 * Refer to the COPYING file of the official project for license.
 *****************************************************************************/
Felix Paul Kühne's avatar
Felix Paul Kühne committed
22

23
#import "VLCMovieViewController.h"
24
#import "VLCExternalDisplayController.h"
25 26
#import "VLCTrackSelectorTableViewCell.h"
#import "VLCTrackSelectorHeaderView.h"
27
#import "VLCEqualizerView.h"
28
#import "VLCMultiSelectionMenuView.h"
29 30
#import "VLCPlaybackController.h"
#import "UIDevice+VLC.h"
31
#import "VLCTimeNavigationTitleView.h"
32 33
#import "VLCPlayerDisplayController.h"
#import "VLCAppDelegate.h"
34
#import "VLCStatusLabel.h"
35
#import "VLCMovieViewControlPanelViewController.h"
Felix Paul Kühne's avatar
Felix Paul Kühne committed
36

37 38
#define FORWARD_SWIPE_DURATION 30
#define BACKWARD_SWIPE_DURATION 10
39

40 41 42
#define TRACK_SELECTOR_TABLEVIEW_CELL @"track selector table view cell"
#define TRACK_SELECTOR_TABLEVIEW_SECTIONHEADER @"track selector table view section header"

43 44 45 46
#define LOCKCHECK \
if (_interfaceIsLocked) \
return

47 48 49 50 51 52 53
typedef NS_ENUM(NSInteger, VLCPanType) {
  VLCPanTypeNone,
  VLCPanTypeBrightness,
  VLCPanTypeSeek,
  VLCPanTypeVolume,
};

54
@interface VLCMovieViewController () <UIGestureRecognizerDelegate, UITableViewDataSource, UITableViewDelegate, VLCMultiSelectionViewDelegate, VLCEqualizerViewUIDelegate>
55
{
56 57 58 59 60 61 62 63 64
    BOOL _controlsHidden;
    BOOL _videoFiltersHidden;
    BOOL _playbackSpeedViewHidden;

    UIActionSheet *_subtitleActionSheet;
    UIActionSheet *_audiotrackActionSheet;

    NSTimer *_idleTimer;

65
    BOOL _viewAppeared;
66
    BOOL _displayRemainingTime;
67
    BOOL _positionSet;
68
    BOOL _playerIsSetup;
69
    BOOL _isScrubbing;
70
    BOOL _interfaceIsLocked;
71
    BOOL _switchingTracksNotChapters;
72
    BOOL _audioOnly;
Ahmad Harb's avatar
Ahmad Harb committed
73

74 75 76 77 78
    BOOL _volumeGestureEnabled;
    BOOL _playPauseGestureEnabled;
    BOOL _brightnessGestureEnabled;
    BOOL _seekGestureEnabled;
    BOOL _closeGestureEnabled;
79
    BOOL _variableJumpDurationEnabled;
80
    UIPinchGestureRecognizer *_pinchRecognizer;
81
    VLCPanType _currentPanType;
Ahmad Harb's avatar
Ahmad Harb committed
82 83 84
    UIPanGestureRecognizer *_panRecognizer;
    UISwipeGestureRecognizer *_swipeRecognizerLeft;
    UISwipeGestureRecognizer *_swipeRecognizerRight;
85 86
    UISwipeGestureRecognizer *_swipeRecognizerUp;
    UISwipeGestureRecognizer *_swipeRecognizerDown;
87
    UITapGestureRecognizer *_tapRecognizer;
88
    UITapGestureRecognizer *_tapOnVideoRecognizer;
89 90 91

    UIView *_trackSelectorContainer;
    UITableView *_trackSelectorTableView;
92 93

    VLCEqualizerView *_equalizerView;
94
    VLCMultiSelectionMenuView *_multiSelectionView;
95 96 97

    UIView *_sleepTimerContainer;
    UIDatePicker *_sleepTimeDatePicker;
98
    NSTimer *_sleepCountDownTimer;
99

100
    NSInteger _mediaDuration;
101 102
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
103 104
@property (nonatomic, strong) UIPopoverController *masterPopoverController;
@property (nonatomic, strong) UIWindow *externalWindow;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
105 106
@end

107
@implementation VLCMovieViewController
Felix Paul Kühne's avatar
Felix Paul Kühne committed
108

109 110 111 112 113 114 115
+ (void)initialize
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *appDefaults = @{kVLCShowRemainingTime : @(YES)};
    [defaults registerDefaults:appDefaults];
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
116 117
- (void)dealloc
{
118 119
    [[NSNotificationCenter defaultCenter] removeObserver:self];

120
    if (_tapRecognizer)
121
        [self.view removeGestureRecognizer:_tapRecognizer];
Ahmad Harb's avatar
Ahmad Harb committed
122
    if (_swipeRecognizerLeft)
123
        [self.view removeGestureRecognizer:_swipeRecognizerLeft];
Ahmad Harb's avatar
Ahmad Harb committed
124
    if (_swipeRecognizerRight)
125
        [self.view removeGestureRecognizer:_swipeRecognizerRight];
126 127 128 129
    if (_swipeRecognizerUp)
        [self.view removeGestureRecognizer:_swipeRecognizerUp];
    if (_swipeRecognizerDown)
        [self.view removeGestureRecognizer:_swipeRecognizerDown];
Ahmad Harb's avatar
Ahmad Harb committed
130
    if (_panRecognizer)
131
        [self.view removeGestureRecognizer:_panRecognizer];
132 133 134 135
    if (_pinchRecognizer)
        [self.view removeGestureRecognizer:_pinchRecognizer];
    [self.view removeGestureRecognizer:_tapOnVideoRecognizer];

136 137 138
    _tapRecognizer = nil;
    _swipeRecognizerLeft = nil;
    _swipeRecognizerRight = nil;
139 140
    _swipeRecognizerUp = nil;
    _swipeRecognizerDown = nil;
141
    _panRecognizer = nil;
142 143
    _pinchRecognizer = nil;
    _tapOnVideoRecognizer = nil;
144 145
}

146
- (void)viewDidLoad
Felix Paul Kühne's avatar
Felix Paul Kühne committed
147
{
148
    [super viewDidLoad];
149 150
    CGRect rect;

151 152
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.edgesForExtendedLayout = UIRectEdgeAll;
153

154 155
    self.videoFilterView.hidden = YES;
    _videoFiltersHidden = YES;
156
    _hueLabel.text = NSLocalizedString(@"VFILTER_HUE", nil);
157 158
    _hueSlider.accessibilityLabel = _hueLabel.text;
    _hueSlider.isAccessibilityElement = YES;
159
    _contrastLabel.text = NSLocalizedString(@"VFILTER_CONTRAST", nil);
160 161
    _contrastSlider.accessibilityLabel = _contrastLabel.text;
    _contrastSlider.isAccessibilityElement = YES;
162
    _brightnessLabel.text = NSLocalizedString(@"VFILTER_BRIGHTNESS", nil);
163 164
    _brightnessSlider.accessibilityLabel = _brightnessLabel.text;
    _brightnessSlider.isAccessibilityElement = YES;
165
    _saturationLabel.text = NSLocalizedString(@"VFILTER_SATURATION", nil);
166 167
    _saturationSlider.accessibilityLabel = _saturationLabel.text;
    _saturationSlider.isAccessibilityElement = YES;
168
    _gammaLabel.text = NSLocalizedString(@"VFILTER_GAMMA", nil);
169 170
    _gammaSlider.accessibilityLabel = _gammaLabel.text;
    _gammaSlider.isAccessibilityElement = YES;
171
    _playbackSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SPEED", nil);
172 173
    _playbackSpeedSlider.accessibilityLabel = _playbackSpeedLabel.text;
    _playbackSpeedSlider.isAccessibilityElement = YES;
174 175 176 177 178 179
    _audioDelayLabel.text = NSLocalizedString(@"AUDIO_DELAY", nil);
    _audioDelaySlider.accessibilityLabel = _audioDelayLabel.text;
    _audioDelaySlider.isAccessibilityElement = YES;
    _spuDelayLabel.text = NSLocalizedString(@"SPU_DELAY", nil);
    _spuDelaySlider.accessibilityLabel = _spuDelayLabel.text;
    _spuDelaySlider.isAccessibilityElement = YES;
180

181
    _resetVideoFilterButton.accessibilityLabel = NSLocalizedString(@"VIDEO_FILTER_RESET_BUTTON", nil);
182
    _resetVideoFilterButton.isAccessibilityElement = YES;
183 184 185
    _sleepTimerButton.accessibilityLabel = NSLocalizedString(@"BUTTON_SLEEP_TIMER", nil);
    _sleepTimerButton.isAccessibilityElement = YES;
    [_sleepTimerButton setTitle:NSLocalizedString(@"BUTTON_SLEEP_TIMER", nil) forState:UIControlStateNormal];
186

187 188 189 190 191 192
    _multiSelectionView = [[VLCMultiSelectionMenuView alloc] init];
    _multiSelectionView.delegate = self;
    _multiSelectionView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    _multiSelectionView.hidden = YES;
    [self.view addSubview:_multiSelectionView];

193
    _scrubHelpLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_HELP", nil);
194

195 196
    self.playbackSpeedView.hidden = YES;
    _playbackSpeedViewHidden = YES;
197

198 199 200 201 202
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(handleExternalScreenDidConnect:)
                   name:UIScreenDidConnectNotification object:nil];
    [center addObserver:self selector:@selector(handleExternalScreenDidDisconnect:)
                   name:UIScreenDidDisconnectNotification object:nil];
203 204
    [center addObserver:self selector:@selector(screenBrightnessChanged:)
                   name:UIScreenBrightnessDidChangeNotification object:nil];
205 206 207 208
    [center addObserver:self
               selector:@selector(appBecameActive:)
                   name:UIApplicationDidBecomeActiveNotification
                 object:nil];
209

210 211
    _playingExternallyTitle.text = NSLocalizedString(@"PLAYING_EXTERNALLY_TITLE", nil);
    _playingExternallyDescription.text = NSLocalizedString(@"PLAYING_EXTERNALLY_DESC", nil);
212
    if ([[UIDevice currentDevice] hasExternalDisplay])
213
        [self showOnExternalDisplay];
214

215 216
    self.trackNameLabel.text = self.artistNameLabel.text = self.albumNameLabel.text = @"";

217
    _movieView.userInteractionEnabled = NO;
218 219 220
    _tapOnVideoRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleControlsVisible)];
    _tapOnVideoRecognizer.delegate = self;
    [self.view addGestureRecognizer:_tapOnVideoRecognizer];
221

222

223

224 225 226 227 228 229
    _pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchGesture:)];
    _pinchRecognizer.delegate = self;
    [self.view addGestureRecognizer:_pinchRecognizer];

    _tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognized)];
    [_tapRecognizer setNumberOfTouchesRequired:2];
230 231

    _currentPanType = VLCPanTypeNone;
232 233 234 235 236 237 238 239
    _panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panRecognized:)];
    [_panRecognizer setMinimumNumberOfTouches:1];
    [_panRecognizer setMaximumNumberOfTouches:1];

    _swipeRecognizerLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRecognized:)];
    _swipeRecognizerLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    _swipeRecognizerRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRecognized:)];
    _swipeRecognizerRight.direction = UISwipeGestureRecognizerDirectionRight;
240 241 242 243 244 245
    _swipeRecognizerUp = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRecognized:)];
    _swipeRecognizerUp.direction = UISwipeGestureRecognizerDirectionUp;
    _swipeRecognizerUp.numberOfTouchesRequired = 2;
    _swipeRecognizerDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRecognized:)];
    _swipeRecognizerDown.direction = UISwipeGestureRecognizerDirectionDown;
    _swipeRecognizerDown.numberOfTouchesRequired = 2;
246 247 248

    [self.view addGestureRecognizer:_swipeRecognizerLeft];
    [self.view addGestureRecognizer:_swipeRecognizerRight];
249 250
    [self.view addGestureRecognizer:_swipeRecognizerUp];
    [self.view addGestureRecognizer:_swipeRecognizerDown];
251 252 253 254
    [self.view addGestureRecognizer:_panRecognizer];
    [self.view addGestureRecognizer:_tapRecognizer];
    [_panRecognizer requireGestureRecognizerToFail:_swipeRecognizerLeft];
    [_panRecognizer requireGestureRecognizerToFail:_swipeRecognizerRight];
255 256
    [_panRecognizer requireGestureRecognizerToFail:_swipeRecognizerUp];
    [_panRecognizer requireGestureRecognizerToFail:_swipeRecognizerDown];
257 258 259 260

    _panRecognizer.delegate = self;
    _swipeRecognizerRight.delegate = self;
    _swipeRecognizerLeft.delegate = self;
261 262
    _swipeRecognizerUp.delegate = self;
    _swipeRecognizerDown.delegate = self;
263
    _tapRecognizer.delegate = self;
264

Felix Paul Kühne's avatar
Felix Paul Kühne committed
265 266 267 268 269 270 271 272 273 274 275
    self.backButton.tintColor = [UIColor colorWithRed:(190.0f/255.0f) green:(190.0f/255.0f) blue:(190.0f/255.0f) alpha:1.];
    self.toolbar.tintColor = [UIColor whiteColor];
    self.toolbar.barStyle = UIBarStyleBlack;

    rect = self.resetVideoFilterButton.frame;
    rect.origin.y = rect.origin.y + 5.;
    self.resetVideoFilterButton.frame = rect;
    rect = self.toolbar.frame;
    rect.size.height = rect.size.height + rect.origin.y;
    rect.origin.y = 0;
    self.toolbar.frame = rect;
276

277
    _playerIsSetup = NO;
278

279 280
    [self.movieView setAccessibilityLabel:NSLocalizedString(@"VO_VIDEOPLAYER_TITLE", nil)];
    [self.movieView setAccessibilityHint:NSLocalizedString(@"VO_VIDEOPLAYER_DOUBLETAP", nil)];
281 282

    rect = self.view.frame;
283 284 285 286 287 288
    CGFloat width;
    CGFloat height;
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        width = 300.;
        height = 320.;
    } else {
289
        width = 420.;
290 291
        height = 470.;
    }
292

293
    _trackSelectorTableView = [[UITableView alloc] initWithFrame:CGRectMake(0., 0., width, height) style:UITableViewStylePlain];
294 295
    _trackSelectorTableView.delegate = self;
    _trackSelectorTableView.dataSource = self;
296
    _trackSelectorTableView.separatorColor = [UIColor clearColor];
297
    _trackSelectorTableView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
298 299 300
    _trackSelectorTableView.rowHeight = 44.;
    _trackSelectorTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _trackSelectorTableView.sectionHeaderHeight = 28.;
301 302
    [_trackSelectorTableView registerClass:[VLCTrackSelectorTableViewCell class] forCellReuseIdentifier:TRACK_SELECTOR_TABLEVIEW_CELL];
    [_trackSelectorTableView registerClass:[VLCTrackSelectorHeaderView class] forHeaderFooterViewReuseIdentifier:TRACK_SELECTOR_TABLEVIEW_SECTIONHEADER];
303
    _trackSelectorTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
304

305
    _trackSelectorContainer = [[VLCFrostedGlasView alloc] initWithFrame:CGRectMake((rect.size.width - width) / 2., (rect.size.height - height) / 2., width, height)];
306
    [_trackSelectorContainer addSubview:_trackSelectorTableView];
307
    _trackSelectorContainer.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleHeight;
308 309 310 311 312 313
    _trackSelectorContainer.hidden = YES;

    if ([[UIDevice currentDevice] speedCategory] >= 3) {
        _trackSelectorTableView.opaque = NO;
        _trackSelectorTableView.backgroundColor = [UIColor clearColor];
    } else
314
        _trackSelectorTableView.backgroundColor = [UIColor blackColor];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
315
    _trackSelectorTableView.allowsMultipleSelection = YES;
316 317

    [self.view addSubview:_trackSelectorContainer];
318

319
    _equalizerView = [[VLCEqualizerView alloc] initWithFrame:CGRectMake(0, 0, 450., 240.)];
320
    _equalizerView.delegate = self.playbackController;
321
    _equalizerView.UIdelegate = self;
322 323 324
    _equalizerView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin;
    _equalizerView.hidden = YES;
    [self.view addSubview:_equalizerView];
325

Felix Paul Kühne's avatar
Felix Paul Kühne committed
326 327 328 329
    /* add sleep timer UI */
    _sleepTimerContainer = [[VLCFrostedGlasView alloc] initWithFrame:CGRectMake(0., 0., 300., 162.)];
    _sleepTimerContainer.center = self.view.center;
    _sleepTimerContainer.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;
330

Felix Paul Kühne's avatar
Felix Paul Kühne committed
331 332 333 334 335 336 337
    _sleepTimeDatePicker = [[UIDatePicker alloc] init];
    if ([[UIDevice currentDevice] speedCategory] >= 3) {
        _sleepTimeDatePicker.opaque = NO;
        _sleepTimeDatePicker.backgroundColor = [UIColor clearColor];
    } else
        _sleepTimeDatePicker.backgroundColor = [UIColor blackColor];
    _sleepTimeDatePicker.tintColor = [UIColor VLCLightTextColor];
338
    _sleepTimeDatePicker.frame = CGRectMake(0., 0., 300., 162.);
Felix Paul Kühne's avatar
Felix Paul Kühne committed
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
    _sleepTimeDatePicker.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;
    [_sleepTimerContainer addSubview:_sleepTimeDatePicker];

    /* adapt the date picker style to suit our needs */
    [_sleepTimeDatePicker setValue:[UIColor whiteColor] forKeyPath:@"textColor"];
    SEL selector = NSSelectorFromString(@"setHighlightsToday:");
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDatePicker instanceMethodSignatureForSelector:selector]];
    BOOL no = NO;
    [invocation setSelector:selector];
    [invocation setArgument:&no atIndex:2];
    [invocation invokeWithTarget:_sleepTimeDatePicker];

    if (_sleepTimerContainer.subviews.count > 0) {
        NSArray *subviewsOfSubview = [_sleepTimeDatePicker.subviews[0] subviews];
        NSUInteger subviewCount = subviewsOfSubview.count;
        for (NSUInteger x = 0; x < subviewCount; x++) {
            if ([subviewsOfSubview[x] isKindOfClass:[UILabel class]])
                [subviewsOfSubview[x] setTextColor:[UIColor VLCLightTextColor]];
        }
358
    }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
359
    _sleepTimeDatePicker.datePickerMode = UIDatePickerModeCountDownTimer;
360
    _sleepTimeDatePicker.minuteInterval = 1;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
361 362 363 364 365
    _sleepTimeDatePicker.minimumDate = [NSDate date];
    _sleepTimeDatePicker.countDownDuration = 1200.;
    [_sleepTimeDatePicker addTarget:self action:@selector(sleepTimerAction:) forControlEvents:UIControlEventValueChanged];

    [self.view addSubview:_sleepTimerContainer];
366 367

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackDidStop:) name:VLCPlaybackControllerPlaybackDidStop object:nil];
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390


    VLCMovieViewControlPanelViewController *panelVC = [[VLCMovieViewControlPanelViewController alloc] initWithNibName:@"VLCMovieViewControlPanel"
                                                                                                               bundle:nil];
    [self addChildViewController:panelVC];
    [self.view addSubview:panelVC.view];
    panelVC.view.translatesAutoresizingMaskIntoConstraints = NO;
    NSArray *hConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[panel]|"
                                                                    options:0
                                                                    metrics:nil
                                                                      views:@{@"panel":panelVC.view}];

    NSArray *vConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[panel]|"
                                                                    options:0
                                                                    metrics:nil
                                                                      views:@{@"panel":panelVC.view}];
    [self.view addConstraints:hConstraints];
    [self.view addConstraints:vConstraints];


    [panelVC didMoveToParentViewController:self];
    self.controlPanelController = panelVC;
    self.controllerPanel = panelVC.view;
391
}
Felix Paul Kühne's avatar
Felix Paul Kühne committed
392

393 394
- (void)viewWillAppear:(BOOL)animated
{
395
    [super viewWillAppear:animated];
396

397 398 399 400 401 402
    /* reset audio meta data views */
    self.artworkImageView.image = nil;
    self.trackNameLabel.text = nil;
    self.artistNameLabel.text = nil;
    self.albumNameLabel.text = nil;

403
    [self.navigationController setNavigationBarHidden:YES animated:animated];
404

405
    VLCPlaybackController *vpc = self.playbackController;
406
    vpc.delegate = self;
407
    [vpc recoverPlaybackState];
408

409
    [self screenBrightnessChanged:nil];
410
    [self setControlsHidden:NO animated:animated];
411 412 413 414

    [self updateDefaults];
    [NSUserDefaults standardUserDefaults];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDefaults) name:NSUserDefaultsDidChangeNotification object:nil];
415 416 417 418 419
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
420
    _viewAppeared = YES;
421

422
    VLCPlaybackController *vpc = self.playbackController;
423
    [vpc recoverDisplayedMetadata];
424 425
    vpc.videoOutputView = nil;
    vpc.videoOutputView = self.movieView;
426 427
}

428
- (void)viewDidLayoutSubviews
429
{
430 431 432 433 434 435

    CGRect equalizerRect = _equalizerView.frame;
    equalizerRect.origin.x = CGRectGetMidX(self.view.bounds) - CGRectGetWidth(equalizerRect)/2.0;
    equalizerRect.origin.y = CGRectGetMidY(self.view.bounds) - CGRectGetHeight(equalizerRect)/2.0;
    _equalizerView.frame = equalizerRect;

436
    CGRect multiSelectionFrame;
437
    CGRect controllerPanelFrame = _controllerPanel.frame;;
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457

    if (UI_USER_INTERFACE_IDIOM() != UIUserInterfaceIdiomPhone) {
        multiSelectionFrame = (CGRect){CGPointMake(0., 0.), [_multiSelectionView proposedDisplaySize]};
        multiSelectionFrame.origin.x = controllerPanelFrame.size.width - multiSelectionFrame.size.width;
        multiSelectionFrame.origin.y = controllerPanelFrame.origin.y - multiSelectionFrame.size.height;
        _multiSelectionView.frame = multiSelectionFrame;
        _multiSelectionView.showsEqualizer = YES;
        return;
    }

    if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)) {
        _multiSelectionView.showsEqualizer = YES;
        multiSelectionFrame = (CGRect){CGPointMake(0., 0.), [_multiSelectionView proposedDisplaySize]};
        multiSelectionFrame.origin.x = controllerPanelFrame.size.width - multiSelectionFrame.size.width;
        multiSelectionFrame.origin.y = controllerPanelFrame.origin.y - multiSelectionFrame.size.height;
    } else {
        _multiSelectionView.showsEqualizer = NO;
        multiSelectionFrame = (CGRect){CGPointMake(0., 0.), [_multiSelectionView proposedDisplaySize]};
        multiSelectionFrame.origin.x = controllerPanelFrame.size.width - multiSelectionFrame.size.width;
        multiSelectionFrame.origin.y = controllerPanelFrame.origin.y - multiSelectionFrame.size.height;
458
    }
459
    _multiSelectionView.frame = multiSelectionFrame;
460 461
}

462
- (void)viewWillDisappear:(BOOL)animated
Felix Paul Kühne's avatar
Felix Paul Kühne committed
463
{
464
    VLCPlaybackController *vpc = self.playbackController;
465 466 467
    if (vpc.videoOutputView == self.movieView) {
        vpc.videoOutputView = nil;
    }
468

469
    _viewAppeared = NO;
470
    if (_idleTimer) {
471
        [_idleTimer invalidate];
472 473
        _idleTimer = nil;
    }
474
    [self.navigationController setNavigationBarHidden:NO animated:YES];
475
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
476
    [super viewWillDisappear:animated];
477

Felix Paul Kühne's avatar
Felix Paul Kühne committed
478 479 480 481
    // hide filter UI for next run
    if (!_videoFiltersHidden)
        _videoFiltersHidden = YES;

482 483 484
    if (_equalizerView.hidden == NO)
        _equalizerView.hidden = YES;

Felix Paul Kühne's avatar
Felix Paul Kühne committed
485 486
    if (!_playbackSpeedViewHidden)
        _playbackSpeedViewHidden = YES;
487

488
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSUserDefaultsDidChangeNotification object:nil];
489
    [[NSUserDefaults standardUserDefaults] setBool:_displayRemainingTime forKey:kVLCShowRemainingTime];
490 491 492 493 494 495 496
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

497 498 499 500 501 502 503 504 505 506 507 508 509 510
- (void) updateDefaults
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    _displayRemainingTime = [[defaults objectForKey:kVLCShowRemainingTime] boolValue];
    [self updateTimeDisplayButton];

    _volumeGestureEnabled = [[defaults objectForKey:kVLCSettingVolumeGesture] boolValue];
    _playPauseGestureEnabled = [[defaults objectForKey:kVLCSettingPlayPauseGesture] boolValue];
    _brightnessGestureEnabled = [[defaults objectForKey:kVLCSettingBrightnessGesture] boolValue];
    _seekGestureEnabled = [[defaults objectForKey:kVLCSettingSeekGesture] boolValue];
    _closeGestureEnabled = [[defaults objectForKey:kVLCSettingCloseGesture] boolValue];
    _variableJumpDurationEnabled = [[defaults objectForKey:kVLCSettingVariableJumpDuration] boolValue];
}

511 512
#pragma mark - controls visibility

513 514
- (void)handlePinchGesture:(UIPinchGestureRecognizer *)recognizer
{
515 516
    LOCKCHECK;

517
    if (!_closeGestureEnabled)
518 519
        return;

520
    if (recognizer.velocity < 0.)
521
        [self minimizePlayback:nil];
522 523
}

524 525
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
526
    if (touch.view != self.view)
527 528 529 530 531
        return NO;

    return YES;
}

Ahmad Harb's avatar
Ahmad Harb committed
532 533 534 535 536
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

537
- (void)setControlsHidden:(BOOL)hidden animated:(BOOL)animated
538
{
539
    _controlsHidden = hidden;
540
    CGFloat alpha = _controlsHidden? 0.0f: 1.0f;
541

542 543
    if (!_controlsHidden) {
        _controllerPanel.alpha = 0.0f;
544
        _controllerPanel.hidden = !_videoFiltersHidden;
545 546
        _toolbar.alpha = 0.0f;
        _toolbar.hidden = NO;
547 548
        _videoFilterView.alpha = 0.0f;
        _videoFilterView.hidden = _videoFiltersHidden;
549 550
        _playbackSpeedView.alpha = 0.0f;
        _playbackSpeedView.hidden = _playbackSpeedViewHidden;
551 552
        _trackSelectorContainer.alpha = 0.0f;
        _trackSelectorContainer.hidden = YES;
553 554
        _equalizerView.alpha = 0.0f;
        _equalizerView.hidden = YES;
555 556 557 558
        if (_sleepTimerContainer) {
            _sleepTimerContainer.alpha = 0.0f;
            _sleepTimerContainer.hidden = YES;
        }
559 560
        _multiSelectionView.alpha = 0.0f;
        _multiSelectionView.hidden = YES;
561 562 563 564

        _artistNameLabel.hidden = NO;
        _albumNameLabel.hidden = NO;
        _trackNameLabel.hidden = NO;
565
    }
566

567 568
    void (^animationBlock)() = ^() {
        _controllerPanel.alpha = alpha;
569
        _toolbar.alpha = alpha;
570
        _videoFilterView.alpha = alpha;
571
        _playbackSpeedView.alpha = alpha;
572
        _trackSelectorContainer.alpha = alpha;
573
        _equalizerView.alpha = alpha;
574
        _multiSelectionView.alpha = alpha;
575 576
        if (_sleepTimerContainer)
            _sleepTimerContainer.alpha = alpha;
577 578 579 580 581

        CGFloat metaInfoAlpha = _audioOnly ? 1.0f : alpha;
        _artistNameLabel.alpha = metaInfoAlpha;
        _albumNameLabel.alpha = metaInfoAlpha;
        _trackNameLabel.alpha = metaInfoAlpha;
582
    };
583

584
    void (^completionBlock)(BOOL finished) = ^(BOOL finished) {
585
        _controllerPanel.hidden = _videoFiltersHidden ? _controlsHidden : NO;
586
        _toolbar.hidden = _controlsHidden;
587
        _videoFilterView.hidden = _videoFiltersHidden;
588
        _playbackSpeedView.hidden = _playbackSpeedViewHidden;
589
        _trackSelectorContainer.hidden = YES;
590
        _equalizerView.hidden = YES;
591 592
        if (_sleepTimerContainer)
            _sleepTimerContainer.hidden = YES;
593
        _multiSelectionView.hidden = YES;
594 595 596 597

        _artistNameLabel.hidden = _audioOnly ? NO : _controlsHidden;
        _albumNameLabel.hidden =  _audioOnly ? NO : _controlsHidden;
        _trackNameLabel.hidden =  _audioOnly ? NO : _controlsHidden;
598
    };
599

600 601
    UIStatusBarAnimation animationType = animated? UIStatusBarAnimationFade: UIStatusBarAnimationNone;
    NSTimeInterval animationDuration = animated? 0.3: 0.0;
602 603

    [[UIApplication sharedApplication] setStatusBarHidden:_viewAppeared ? _controlsHidden : NO withAnimation:animationType];
604 605
    [UIView animateWithDuration:animationDuration animations:animationBlock completion:completionBlock];
}
606

607
- (void)toggleControlsVisible
608
{
609 610 611 612 613
    if (!_trackSelectorContainer.hidden) {
        for (UIGestureRecognizer *recognizer in self.view.gestureRecognizers)
            [recognizer setEnabled:YES];
    }

614 615 616
    if (_controlsHidden && !_videoFiltersHidden)
        _videoFiltersHidden = YES;

617
    [self setControlsHidden:!_controlsHidden animated:YES];
618 619
}

620
- (void)_resetIdleTimer
621 622
{
    if (!_idleTimer)
623
        _idleTimer = [NSTimer scheduledTimerWithTimeInterval:4.
624 625 626 627 628
                                                      target:self
                                                    selector:@selector(idleTimerExceeded)
                                                    userInfo:nil
                                                     repeats:NO];
    else {
629 630
        if (fabs([_idleTimer.fireDate timeIntervalSinceNow]) < 4.)
            [_idleTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:4.]];
631 632 633 634 635 636 637
    }
}

- (void)idleTimerExceeded
{
    _idleTimer = nil;
    if (!_controlsHidden)
638
        [self toggleControlsVisible];
639

640 641 642
    if (!_videoFiltersHidden)
        _videoFiltersHidden = YES;

643 644 645
    if (_equalizerView.hidden == NO)
        _equalizerView.hidden = YES;

646 647 648
    if (!_playbackSpeedViewHidden)
        _playbackSpeedViewHidden = YES;

Felix Paul Kühne's avatar
Felix Paul Kühne committed
649 650
    if (self.scrubIndicatorView.hidden == NO)
        self.scrubIndicatorView.hidden = YES;
651 652
}

653 654
- (UIResponder *)nextResponder
{
655
    [self _resetIdleTimer];
656 657 658
    return [super nextResponder];
}

659 660 661 662
#pragma mark - controls

- (IBAction)closePlayback:(id)sender
{
663
    LOCKCHECK;
664 665
    [[VLCPlaybackController sharedInstance] stopPlayback];
}
666

667 668 669 670
- (IBAction)minimizePlayback:(id)sender
{
    LOCKCHECK;
    [[UIApplication sharedApplication] sendAction:@selector(closeFullscreenPlayback) to:nil from:self forEvent:nil];
671
}
672

673 674
- (IBAction)positionSliderAction:(UISlider *)sender
{
675 676
    LOCKCHECK;

677 678 679
    /* we need to limit the number of events sent by the slider, since otherwise, the user
     * wouldn't see the I-frames when seeking on current mobile devices. This isn't a problem
     * within the Simulator, but especially on older ARMv7 devices, it's clearly noticeable. */
680
    [self performSelector:@selector(_setPositionForReal) withObject:nil afterDelay:0.3];
681
    if (_mediaDuration > 0) {
682 683
        VLCTime *newPosition = [VLCTime timeWithInt:(int)(sender.value * _mediaDuration)];
        [self.timeNavigationTitleView.timeDisplayButton setTitle:newPosition.stringValue forState:UIControlStateNormal];
684
        [self.timeNavigationTitleView setNeedsLayout];
685
        self.timeNavigationTitleView.timeDisplayButton.accessibilityLabel = [NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"PLAYBACK_POSITION", nil), newPosition.stringValue];
686 687
        _positionSet = NO;
    }
688
    [self _resetIdleTimer];
689 690
}

691 692 693
- (void)_setPositionForReal
{
    if (!_positionSet) {
694 695
        self.playbackController.mediaPlayer.position = self.timeNavigationTitleView.positionSlider.value;
        [self.playbackController setNeedsMetadataUpdate];
696 697 698 699
        _positionSet = YES;
    }
}

700 701
- (IBAction)positionSliderTouchDown:(id)sender
{
702 703
    LOCKCHECK;

704 705
    [self _updateScrubLabel];
    self.scrubIndicatorView.hidden = NO;
706
    _isScrubbing = YES;
707 708 709 710
}

- (IBAction)positionSliderTouchUp:(id)sender
{
711 712
    LOCKCHECK;

713
    self.scrubIndicatorView.hidden = YES;
714
    _isScrubbing = NO;
715 716 717 718
}

- (void)_updateScrubLabel
{
719
    float speed = self.timeNavigationTitleView.positionSlider.scrubbingSpeed;
720
    if (speed == 1.)
721
        self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_HIGH", nil);
722
    else if (speed == .5)
723
        self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_HALF", nil);
724
    else if (speed == .25)
725
        self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_QUARTER", nil);
726
    else
727
        self.currentScrubSpeedLabel.text = NSLocalizedString(@"PLAYBACK_SCRUB_FINE", nil);
728 729

    [self _resetIdleTimer];
730 731 732 733
}

- (IBAction)positionSliderDrag:(id)sender
{
734 735
    LOCKCHECK;

736 737 738
    [self _updateScrubLabel];
}

739 740
- (IBAction)volumeSliderAction:(id)sender
{
741 742
    LOCKCHECK;

743 744 745
    [self _resetIdleTimer];
}

746 747


748 749 750 751 752 753 754 755 756 757 758
- (void)updateTimeDisplayButton
{
    VLCMediaPlayer *mediaPlayer = self.playbackController.mediaPlayer;
    UIButton *timeDisplayButton = self.timeNavigationTitleView.timeDisplayButton;
    if (_displayRemainingTime)
        [timeDisplayButton setTitle:[[mediaPlayer remainingTime] stringValue] forState:UIControlStateNormal];
    else
        [timeDisplayButton setTitle:[[mediaPlayer time] stringValue] forState:UIControlStateNormal];
    [self.timeNavigationTitleView setNeedsLayout];
}

759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
- (void)updateSleepTimerButton
{
    NSMutableString *title = [NSMutableString stringWithString:NSLocalizedString(@"BUTTON_SLEEP_TIMER", nil)];
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
    if (vpc.sleepTimer != nil && vpc.sleepTimer.valid) {
        int remainSeconds = (int)[vpc.sleepTimer.fireDate timeIntervalSinceNow];
        int hour = remainSeconds / 3600;
        int minute = (remainSeconds - hour * 3600) / 60;
        int second = remainSeconds % 60;
        [title appendFormat:@"  %02d:%02d:%02d", hour, minute, second];
    } else {
        [_sleepCountDownTimer invalidate];
    }

    [_sleepTimerButton setTitle:title forState:UIControlStateNormal];
}

776 777
#pragma mark - playback controller delegation

778 779 780 781 782 783 784 785
- (VLCPlaybackController *)playbackController
{
    if (!_playbackController) {
        _playbackController = [VLCPlaybackController sharedInstance];
    }
    return _playbackController;
}

786
- (void)playbackPositionUpdated:(VLCPlaybackController *)controller
787
{
788
    VLCMediaPlayer *mediaPlayer = controller.mediaPlayer;
789
    if (!_isScrubbing) {
790
        self.timeNavigationTitleView.positionSlider.value = [mediaPlayer position];
791 792
    }

793
    [self updateTimeDisplayButton];
794 795
}

796
- (void)prepareForMediaPlayback:(VLCPlaybackController *)controller
797
{
798
    self.trackNameLabel.text = self.artistNameLabel.text = self.albumNameLabel.text = @"";
799 800 801
    self.timeNavigationTitleView.positionSlider.value = 0.;
    [self.timeNavigationTitleView.timeDisplayButton setTitle:@"" forState:UIControlStateNormal];
    self.timeNavigationTitleView.timeDisplayButton.accessibilityLabel = @"";
802 803 804 805
    if (![[UIDevice currentDevice] hasExternalDisplay])
        self.brightnessSlider.value = [UIScreen mainScreen].brightness * 2.;
    [_equalizerView reloadData];

806
    double playbackRate = controller.playbackRate;
807 808
    self.playbackSpeedSlider.value = log2(playbackRate);
    self.playbackSpeedIndicator.text = [NSString stringWithFormat:@"%.2fx", playbackRate];
809

810 811
    float audioDelay = controller.audioDelay;
    self.audioDelaySlider.value = audioDelay;
812
    self.audioDelayIndicator.text = [NSString stringWithFormat:@"%1.2f s", audioDelay];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
813

814 815 816
    float subtitleDelay = controller.subtitleDelay;
    self.spuDelaySlider.value = subtitleDelay;
    self.spuDelayIndicator.text = [NSString stringWithFormat:@"%1.00f s", subtitleDelay];
817 818 819 820

    [self _resetIdleTimer];
}

821
- (void)playbackDidStop:(NSNotification *)notification
822
{
823
    [self minimizePlayback:nil];
824 825 826 827 828 829 830 831 832 833 834 835
}

- (void)mediaPlayerStateChanged:(VLCMediaPlayerState)currentState
                      isPlaying:(BOOL)isPlaying
currentMediaHasTrackToChooseFrom:(BOOL)currentMediaHasTrackToChooseFrom
        currentMediaHasChapters:(BOOL)currentMediaHasChapters
          forPlaybackController:(VLCPlaybackController *)controller
{
    if (currentState == VLCMediaPlayerStateBuffering)
        _mediaDuration = controller.mediaDuration;

    if (currentState == VLCMediaPlayerStateError)
836
        [self.statusLabel showStatusMessage:NSLocalizedString(@"PLAYBACK_FAILED", nil)];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
837

838
    [self.controlPanelController updateButtons];
839

840
    _multiSelectionView.mediaHasChapters = currentMediaHasChapters;
841 842 843 844
}

- (void)showStatusMessage:(NSString *)statusMessage forPlaybackController:(VLCPlaybackController *)controller
{
845
    [self showStatusMessage:statusMessage];
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
}

- (void)displayMetadataForPlaybackController:(VLCPlaybackController *)controller
                                       title:(NSString *)title
                                     artwork:(UIImage *)artwork
                                      artist:(NSString *)artist
                                       album:(NSString *)album
                                   audioOnly:(BOOL)audioOnly
{
    if (!_viewAppeared)
        return;

    self.trackNameLabel.text</