VLCFullscreenMovieTVViewController.m 34.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
/*****************************************************************************
 * VLC for iOS
 *****************************************************************************
 * Copyright (c) 2015 VideoLAN. All rights reserved.
 * $Id$
 *
 * Authors: Felix Paul Kühne <fkuehne # videolan.org>
 *
 * Refer to the COPYING file of the official project for license.
 *****************************************************************************/

#import "VLCFullscreenMovieTVViewController.h"
13
#import "VLCPlaybackInfoTVViewController.h"
14
#import "VLCPlaybackInfoTVAnimators.h"
15
#import "VLCIRTVTapGestureRecognizer.h"
16
#import "VLCHTTPUploaderController.h"
17
#import "VLCSiriRemoteGestureRecognizer.h"
18
#import "VLCNetworkImageView.h"
19
#import "VLCMetaData.h"
20

21 22 23 24 25 26 27
typedef NS_ENUM(NSInteger, VLCPlayerScanState)
{
    VLCPlayerScanStateNone,
    VLCPlayerScanStateForward2,
    VLCPlayerScanStateForward4,
};

28
@interface VLCFullscreenMovieTVViewController (UIViewControllerTransitioningDelegate) <UIViewControllerTransitioningDelegate, UIGestureRecognizerDelegate>
29
@end
30

31
@interface VLCFullscreenMovieTVViewController ()
32

33 34
@property (nonatomic) CADisplayLink *displayLink;
@property (nonatomic) NSTimer *audioDescriptionScrollTimer;
35
@property (nonatomic) NSTimer *hidePlaybackControlsViewAfterDeleayTimer;
36
@property (nonatomic) VLCPlaybackInfoTVViewController *infoViewController;
37 38
@property (nonatomic) NSNumber *scanSavedPlaybackRate;
@property (nonatomic) VLCPlayerScanState scanState;
39 40
@property (nonatomic) NSString *lastArtist;

41 42
@property (nonatomic, readonly, getter=isSeekable) BOOL seekable;

43 44
@property (nonatomic) NSSet<UIGestureRecognizer *> *simultaneousGestureRecognizers;

45 46 47 48
@end

@implementation VLCFullscreenMovieTVViewController

49 50 51 52 53
+ (instancetype)fullscreenMovieTVViewController
{
    return [[self alloc] initWithNibName:nil bundle:nil];
}

54 55
- (void)viewDidLoad
{
56 57 58 59 60
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.edgesForExtendedLayout = UIRectEdgeAll;

    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self
61
               selector:@selector(playbackDidStop)
62 63
                   name:VLCPlaybackControllerPlaybackDidStop
                 object:nil];
64 65 66 67
    [center addObserver:self
               selector:@selector(playbackDidStop)
                   name:VLCPlaybackControllerPlaybackDidFail
                 object:nil];
68 69

    _movieView.userInteractionEnabled = NO;
70

71 72 73 74 75 76 77
    self.titleLabel.text = @"";

    self.transportBar.bufferStartFraction = 0.0;
    self.transportBar.bufferEndFraction = 1.0;
    self.transportBar.playbackFraction = 0.0;
    self.transportBar.scrubbingFraction = 0.0;

78
    self.dimmingView.alpha = 0.0;
79
    self.bottomOverlayView.alpha = 0.0;
Tobias's avatar
Tobias committed
80

Felix Paul Kühne's avatar
Felix Paul Kühne committed
81
    self.bufferingLabel.text = NSLocalizedString(@"PLEASE_WAIT", nil);
82

83
    NSMutableSet<UIGestureRecognizer *> *simultaneousGestureRecognizers = [NSMutableSet set];
84

85
    // Panning and Swiping
Tobias's avatar
Tobias committed
86
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
87
    panGestureRecognizer.delegate = self;
Tobias's avatar
Tobias committed
88
    [self.view addGestureRecognizer:panGestureRecognizer];
89
    [simultaneousGestureRecognizers addObject:panGestureRecognizer];
Tobias's avatar
Tobias committed
90

91 92 93 94 95
    // Button presses
    UITapGestureRecognizer *playpauseGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playPausePressed)];
    playpauseGesture.allowedPressTypes = @[@(UIPressTypePlayPause)];
    [self.view addGestureRecognizer:playpauseGesture];

96 97
    UITapGestureRecognizer *menuTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuButtonPressed:)];
    menuTapGestureRecognizer.allowedPressTypes = @[@(UIPressTypeMenu)];
98
    menuTapGestureRecognizer.delegate = self;
99
    [self.view addGestureRecognizer:menuTapGestureRecognizer];
100

101
    // IR only recognizer
102 103 104 105
    UITapGestureRecognizer *upArrowRecognizer = [[VLCIRTVTapGestureRecognizer alloc] initWithTarget:self action:@selector(handleIRPressUp)];
    upArrowRecognizer.allowedPressTypes = @[@(UIPressTypeUpArrow)];
    [self.view addGestureRecognizer:upArrowRecognizer];

106 107 108
    UITapGestureRecognizer *downArrowRecognizer = [[VLCIRTVTapGestureRecognizer alloc] initWithTarget:self action:@selector(showInfoVCIfNotScrubbing)];
    downArrowRecognizer.allowedPressTypes = @[@(UIPressTypeDownArrow)];
    [self.view addGestureRecognizer:downArrowRecognizer];
109

110 111 112 113 114 115 116
    UITapGestureRecognizer *leftArrowRecognizer = [[VLCIRTVTapGestureRecognizer alloc] initWithTarget:self action:@selector(handleIRPressLeft)];
    leftArrowRecognizer.allowedPressTypes = @[@(UIPressTypeLeftArrow)];
    [self.view addGestureRecognizer:leftArrowRecognizer];

    UITapGestureRecognizer *rightArrowRecognizer = [[VLCIRTVTapGestureRecognizer alloc] initWithTarget:self action:@selector(handleIRPressRight)];
    rightArrowRecognizer.allowedPressTypes = @[@(UIPressTypeRightArrow)];
    [self.view addGestureRecognizer:rightArrowRecognizer];
117 118 119 120 121

    // Siri remote arrow presses
    VLCSiriRemoteGestureRecognizer *siriArrowRecognizer = [[VLCSiriRemoteGestureRecognizer alloc] initWithTarget:self action:@selector(handleSiriRemote:)];
    siriArrowRecognizer.delegate = self;
    [self.view addGestureRecognizer:siriArrowRecognizer];
122 123 124
    [simultaneousGestureRecognizers addObject:siriArrowRecognizer];

    self.simultaneousGestureRecognizers = simultaneousGestureRecognizers;
125

126
    [super viewDidLoad];
127 128
}

129 130 131 132 133 134
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    self.infoViewController = nil;
}

135 136
#pragma mark - view events

137 138 139 140
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

141
    self.audioView.hidden = YES;
142 143 144 145
    self.audioDescriptionTextView.hidden = YES;
    self.audioTitleLabel.hidden = YES;
    self.audioArtistLabel.hidden = YES;
    self.audioAlbumNameLabel.hidden = YES;
146 147 148 149 150
    self.audioArtworkImageView.image = [UIImage imageNamed:@"about-app-icon"];
    self.audioLargeBackgroundImageView.image = [UIImage imageNamed:@"about-app-icon"];
    self.audioArtworkImageView.animateImageSetting = YES;
    self.audioLargeBackgroundImageView.animateImageSetting = YES;

151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
    vpc.delegate = self;
    [vpc recoverPlaybackState];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
    [vpc recoverDisplayedMetadata];
    vpc.videoOutputView = nil;
    vpc.videoOutputView = self.movieView;
}

- (void)viewWillDisappear:(BOOL)animated
{
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
    if (vpc.videoOutputView == self.movieView) {
        vpc.videoOutputView = nil;
    }

173
    [vpc stopPlayback];
174

175 176
    [self stopAudioDescriptionAnimation];

177 178 179 180 181 182 183
    /* delete potentially downloaded subs */
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString* tempSubsDirPath = [searchPaths[0] stringByAppendingPathComponent:@"tempsubs"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:tempSubsDirPath])
        [fileManager removeItemAtPath:tempSubsDirPath error:nil];

184
    [super viewWillDisappear:animated];
185 186
}

187 188 189 190 191
- (BOOL)canBecomeFirstResponder
{
    return YES;
}

Tobias's avatar
Tobias committed
192
#pragma mark - UIActions
Tobias's avatar
Tobias committed
193
- (void)playPausePressed
Tobias's avatar
Tobias committed
194
{
195 196
    [self showPlaybackControlsIfNeededForUserInteraction];

197 198
    [self setScanState:VLCPlayerScanStateNone];

Tobias's avatar
Tobias committed
199
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
200
    if (self.transportBar.scrubbing) {
201
        [self selectButtonPressed];
202 203 204
    } else {
        [vpc playPause];
    }
Tobias's avatar
Tobias committed
205 206
}

Tobias's avatar
Tobias committed
207 208
- (void)panGesture:(UIPanGestureRecognizer *)panGestureRecognizer
{
209 210 211 212
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
    NSInteger currentTitle = [vpc indexOfCurrentTitle];
    if (currentTitle < [vpc numberOfTitles]) {
        NSDictionary *title = [vpc titleDescriptionsDictAtIndex:currentTitle];
213 214 215 216 217
        if ([[title objectForKey:VLCTitleDescriptionIsMenu] boolValue]) {
            return;
        }
    }

218 219 220 221 222 223 224
    switch (panGestureRecognizer.state) {
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateFailed:
            return;
        default:
            break;
    }
225

Tobias's avatar
Tobias committed
226 227 228 229
    VLCTransportBar *bar = self.transportBar;

    UIView *view = self.view;
    CGPoint translation = [panGestureRecognizer translationInView:view];
230
    BOOL canScrub = self.canScrub;
Tobias's avatar
Tobias committed
231 232

    if (!bar.scrubbing) {
233
        if (ABS(translation.x) > 150.0) {
234
            if (self.isSeekable && canScrub) {
235 236 237 238
                [self startScrubbing];
            } else {
                return;
            }
239
        } else if (translation.y > 200.0) {
240 241
            panGestureRecognizer.enabled = NO;
            panGestureRecognizer.enabled = YES;
242 243
            [self showInfoVCIfNotScrubbing];
            return;
Tobias's avatar
Tobias committed
244 245 246 247
        } else {
            return;
        }
    }
248

249 250 251 252
    if (!canScrub) {
        return;
    }

253
    [self showPlaybackControlsIfNeededForUserInteraction];
254
    [self setScanState:VLCPlayerScanStateNone];
255

Tobias's avatar
Tobias committed
256
    const CGFloat scaleFactor = 8.0;
257
    CGFloat fractionInView = translation.x / CGRectGetWidth(view.bounds) / scaleFactor;
258
    CGFloat scrubbingFraction = MAX(0.0, MIN(bar.scrubbingFraction + fractionInView,1.0));
259

260
    if (ABS(scrubbingFraction - bar.playbackFraction)<0.005) {
261 262 263 264 265 266 267 268 269 270 271 272 273
        scrubbingFraction = bar.playbackFraction;
    } else {
        translation.x = 0.0;
        [panGestureRecognizer setTranslation:translation inView:view];
    }

    [UIView animateWithDuration:0.3
                          delay:0.0
                        options:UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionBeginFromCurrentState
                     animations:^{
                         bar.scrubbingFraction = scrubbingFraction;
                     }
                     completion:nil];
274 275 276
    [self updateTimeLabelsForScrubbingFraction:scrubbingFraction];
}

277
- (void)selectButtonPressed
278
{
279 280 281 282
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
    NSInteger currentTitle = [vpc indexOfCurrentTitle];
    if (currentTitle < [vpc numberOfTitles]) {
        NSDictionary *title = [vpc titleDescriptionsDictAtIndex:currentTitle];
283
        if ([[title objectForKey:VLCTitleDescriptionIsMenu] boolValue]) {
284
            [vpc performNavigationAction:VLCMediaPlaybackNavigationActionActivate];
285 286 287 288
            return;
        }
    }

289
    [self showPlaybackControlsIfNeededForUserInteraction];
290
    [self setScanState:VLCPlayerScanStateNone];
291

292 293
    VLCTransportBar *bar = self.transportBar;
    if (bar.scrubbing) {
294
        bar.playbackFraction = bar.scrubbingFraction;
295
        [self stopScrubbing];
296
        [vpc setPlaybackPosition:bar.scrubbingFraction];
297
    } else {
298
        [vpc playPause];
299 300 301 302 303 304 305 306 307 308 309 310
    }
}
- (void)menuButtonPressed:(UITapGestureRecognizer *)recognizer
{
    VLCTransportBar *bar = self.transportBar;
    if (bar.scrubbing) {
        [UIView animateWithDuration:0.3 animations:^{
            bar.scrubbingFraction = bar.playbackFraction;
            [bar layoutIfNeeded];
        }];
        [self updateTimeLabelsForScrubbingFraction:bar.playbackFraction];
        [self stopScrubbing];
311
        [self hidePlaybackControlsIfNeededAfterDelay];
312 313 314
    }
}

315
- (void)showInfoVCIfNotScrubbing
316
{
317 318 319 320
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
    NSInteger currentTitle = [vpc indexOfCurrentTitle];
    if (currentTitle < [vpc numberOfTitles]) {
        NSDictionary *title = [vpc titleDescriptionsDictAtIndex:currentTitle];
321
        if ([[title objectForKey:VLCTitleDescriptionIsMenu] boolValue]) {
322
            [vpc performNavigationAction:VLCMediaPlaybackNavigationActionDown];
323 324 325 326
            return;
        }
    }

327 328 329 330
    if (self.transportBar.scrubbing) {
        return;
    }
    // TODO: configure with player info
331
    VLCPlaybackInfoTVViewController *infoViewController = self.infoViewController;
332 333 334 335 336

    // prevent repeated presentation when users repeatedly and quickly press the arrow button
    if (infoViewController.isBeingPresented) {
        return;
    }
337 338
    infoViewController.transitioningDelegate = self;
    [self presentViewController:infoViewController animated:YES completion:nil];
339
    [self animatePlaybackControlsToVisibility:NO];
340 341
}

342 343
- (void)handleIRPressUp
{
344 345 346 347
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
    NSInteger currentTitle = [vpc indexOfCurrentTitle];
    if (currentTitle < [vpc numberOfTitles]) {
        NSDictionary *title = [vpc titleDescriptionsDictAtIndex:currentTitle];
348
        if ([[title objectForKey:VLCTitleDescriptionIsMenu] boolValue]) {
349
            [vpc performNavigationAction:VLCMediaPlaybackNavigationActionUp];
350 351 352 353
        }
    }
}

354 355
- (void)handleIRPressLeft
{
356 357 358 359
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
    NSInteger currentTitle = [vpc indexOfCurrentTitle];
    if (currentTitle < [vpc numberOfTitles]) {
        NSDictionary *title = [vpc titleDescriptionsDictAtIndex:currentTitle];
360
        if ([[title objectForKey:VLCTitleDescriptionIsMenu] boolValue]) {
361
            [vpc performNavigationAction:VLCMediaPlaybackNavigationActionLeft];
362 363 364 365
            return;
        }
    }

366
    [self showPlaybackControlsIfNeededForUserInteraction];
367 368 369 370 371

    if (!self.isSeekable) {
        return;
    }

372 373 374 375 376 377 378 379 380 381 382
    BOOL paused = ![VLCPlaybackController sharedInstance].isPlaying;
    if (paused) {
        [self jumpBackward];
    } else
    {
        [self scanForwardPrevious];
    }
}

- (void)handleIRPressRight
{
383 384 385 386
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
    NSInteger currentTitle = [vpc indexOfCurrentTitle];
    if (currentTitle < [vpc numberOfTitles]) {
        NSDictionary *title = [vpc titleDescriptionsDictAtIndex:currentTitle];
387
        if ([[title objectForKey:VLCTitleDescriptionIsMenu] boolValue]) {
388
            [vpc performNavigationAction:VLCMediaPlaybackNavigationActionRight];
389 390 391 392
            return;
        }
    }

393
    [self showPlaybackControlsIfNeededForUserInteraction];
394 395 396 397 398

    if (!self.isSeekable) {
        return;
    }

399 400 401 402 403 404 405 406
    BOOL paused = ![VLCPlaybackController sharedInstance].isPlaying;
    if (paused) {
        [self jumpForward];
    } else {
        [self scanForwardNext];
    }
}

407 408
- (void)handleSiriRemote:(VLCSiriRemoteGestureRecognizer *)recognizer
{
409 410 411 412
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
    NSInteger currentTitle = [vpc indexOfCurrentTitle];
    if (currentTitle < [vpc numberOfTitles]) {
        NSDictionary *title = [vpc titleDescriptionsDictAtIndex:currentTitle];
413 414 415 416 417
        if ([[title objectForKey:VLCTitleDescriptionIsMenu] boolValue]) {
            switch (recognizer.state) {
                case UIGestureRecognizerStateBegan:
                case UIGestureRecognizerStateChanged:
                    if (recognizer.isLongPress) {
418
                        [vpc performNavigationAction:VLCMediaPlaybackNavigationActionActivate];
419
                        break;
420 421 422 423
                    }
                    break;
                case UIGestureRecognizerStateEnded:
                    if (recognizer.isClick && !recognizer.isLongPress) {
424
                        [vpc performNavigationAction:VLCMediaPlaybackNavigationActionActivate];
425 426 427
                    } else {
                        switch (recognizer.touchLocation) {
                            case VLCSiriRemoteTouchLocationLeft:
428
                                [vpc performNavigationAction:VLCMediaPlaybackNavigationActionLeft];
429 430
                                break;
                            case VLCSiriRemoteTouchLocationRight:
431
                                [vpc performNavigationAction:VLCMediaPlaybackNavigationActionRight];
432 433
                                break;
                            case VLCSiriRemoteTouchLocationUp:
434
                                [vpc performNavigationAction:VLCMediaPlaybackNavigationActionUp];
435 436
                                break;
                            case VLCSiriRemoteTouchLocationDown:
437
                                [vpc performNavigationAction:VLCMediaPlaybackNavigationActionDown];
438 439 440 441 442 443 444 445 446 447 448 449 450 451
                                break;
                            case VLCSiriRemoteTouchLocationUnknown:
                                break;
                        }
                    }
                    break;
                default:
                    break;
            }
            return;
        }
    }


452
    [self showPlaybackControlsIfNeededForUserInteraction];
453

454 455 456 457 458
    VLCTransportBarHint hint = self.transportBar.hint;
    switch (recognizer.state) {
        case UIGestureRecognizerStateBegan:
        case UIGestureRecognizerStateChanged:
            if (recognizer.isLongPress) {
459
                if (!self.isSeekable && recognizer.touchLocation == VLCSiriRemoteTouchLocationRight) {
460 461 462 463
                    [self setScanState:VLCPlayerScanStateForward2];
                    return;
                }
            } else {
464 465 466 467 468 469 470 471 472 473 474 475 476 477
                if (self.canJump) {
                    switch (recognizer.touchLocation) {
                        case VLCSiriRemoteTouchLocationLeft:
                            hint = VLCTransportBarHintJumpBackward10;
                            break;
                        case VLCSiriRemoteTouchLocationRight:
                            hint = VLCTransportBarHintJumpForward10;
                            break;
                        default:
                            hint = VLCTransportBarHintNone;
                            break;
                    }
                } else {
                    hint = VLCTransportBarHintNone;
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
                }
            }
            break;
        case UIGestureRecognizerStateEnded:
            if (recognizer.isClick && !recognizer.isLongPress) {
                [self handleSiriPressUpAtLocation:recognizer.touchLocation];
            }
            [self setScanState:VLCPlayerScanStateNone];
            break;
        case UIGestureRecognizerStateCancelled:
            hint = VLCTransportBarHintNone;
            [self setScanState:VLCPlayerScanStateNone];
            break;
        default:
            break;
    }
494
    self.transportBar.hint = self.isSeekable ? hint : VLCPlayerScanStateNone;
495 496 497 498
}

- (void)handleSiriPressUpAtLocation:(VLCSiriRemoteTouchLocation)location
{
499
    BOOL canJump = [self canJump];
500 501
    switch (location) {
        case VLCSiriRemoteTouchLocationLeft:
502
            if (canJump && self.isSeekable) {
503 504
                [self jumpBackward];
            }
505 506
            break;
        case VLCSiriRemoteTouchLocationRight:
507
            if (canJump && self.isSeekable) {
508 509
                [self jumpForward];
            }
510
            break;
511 512 513 514 515 516
        default:
            [self selectButtonPressed];
            break;
    }
}

517 518 519 520
#pragma mark -
static const NSInteger VLCJumpInterval = 10000; // 10 seconds
- (void)jumpForward
{
521 522
    NSAssert(self.isSeekable, @"Tried to seek while not media is not seekable.");

523 524
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];

525
    if (vpc.isPlaying) {
526
        [self jumpInterval:VLCJumpInterval];
527 528 529
    } else {
        [self scrubbingJumpInterval:VLCJumpInterval];
    }
530 531 532
}
- (void)jumpBackward
{
533 534
    NSAssert(self.isSeekable, @"Tried to seek while not media is not seekable.");

535 536
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];

537
    if (vpc.isPlaying) {
538
        [self jumpInterval:-VLCJumpInterval];
539 540 541
    } else {
        [self scrubbingJumpInterval:-VLCJumpInterval];
    }
542 543
}

544 545
- (void)jumpInterval:(NSInteger)interval
{
546 547
    NSAssert(self.isSeekable, @"Tried to seek while not media is not seekable.");

548 549 550 551 552 553 554
    NSInteger duration = [VLCPlaybackController sharedInstance].mediaDuration;
    if (duration==0) {
        return;
    }
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];

    CGFloat intervalFraction = ((CGFloat)interval)/((CGFloat)duration);
555
    CGFloat currentFraction = vpc.playbackPosition;
556
    currentFraction += intervalFraction;
557
    vpc.playbackPosition = currentFraction;
558 559
}

560
- (void)scrubbingJumpInterval:(NSInteger)interval
561
{
562 563
    NSAssert(self.isSeekable, @"Tried to seek while not media is not seekable.");

564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
    NSInteger duration = [VLCPlaybackController sharedInstance].mediaDuration;
    if (duration==0) {
        return;
    }
    CGFloat intervalFraction = ((CGFloat)interval)/((CGFloat)duration);
    VLCTransportBar *bar = self.transportBar;
    bar.scrubbing = YES;
    CGFloat currentFraction = bar.scrubbingFraction;
    currentFraction += intervalFraction;
    bar.scrubbingFraction = currentFraction;
    [self updateTimeLabelsForScrubbingFraction:currentFraction];
}

- (void)scanForwardNext
{
579 580
    NSAssert(self.isSeekable, @"Tried to seek while not media is not seekable.");

581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
    VLCPlayerScanState nextState = self.scanState;
    switch (self.scanState) {
        case VLCPlayerScanStateNone:
            nextState = VLCPlayerScanStateForward2;
            break;
        case VLCPlayerScanStateForward2:
            nextState = VLCPlayerScanStateForward4;
            break;
        case VLCPlayerScanStateForward4:
            return;
        default:
            return;
    }
    [self setScanState:nextState];
}

- (void)scanForwardPrevious
{
599 600
    NSAssert(self.isSeekable, @"Tried to seek while not media is not seekable.");

601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
    VLCPlayerScanState nextState = self.scanState;
    switch (self.scanState) {
        case VLCPlayerScanStateNone:
            return;
        case VLCPlayerScanStateForward2:
            nextState = VLCPlayerScanStateNone;
            break;
        case VLCPlayerScanStateForward4:
            nextState = VLCPlayerScanStateForward2;
            break;
        default:
            return;
    }
    [self setScanState:nextState];
}


- (void)setScanState:(VLCPlayerScanState)scanState
{
620 621 622 623
    if (_scanState == scanState) {
        return;
    }

624 625
    NSAssert(self.isSeekable || scanState == VLCPlayerScanStateNone, @"Tried to seek while media not seekable.");

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
    if (_scanState == VLCPlayerScanStateNone) {
        self.scanSavedPlaybackRate = @([VLCPlaybackController sharedInstance].playbackRate);
    }
    _scanState = scanState;
    float rate = 1.0;
    VLCTransportBarHint hint = VLCTransportBarHintNone;
    switch (scanState) {
        case VLCPlayerScanStateForward2:
            rate = 2.0;
            hint = VLCTransportBarHintScanForward;
            break;
        case VLCPlayerScanStateForward4:
            rate = 4.0;
            hint = VLCTransportBarHintScanForward;
            break;

        case VLCPlayerScanStateNone:
        default:
            rate = self.scanSavedPlaybackRate.floatValue ?: 1.0;
            hint = VLCTransportBarHintNone;
            self.scanSavedPlaybackRate = nil;
            break;
    }

    [VLCPlaybackController sharedInstance].playbackRate = rate;
    [self.transportBar setHint:hint];
}
653 654 655

- (BOOL)isSeekable
{
656
    return [[VLCPlaybackController sharedInstance] isSeekable];
657 658
}

659 660 661 662 663 664 665 666 667 668 669
- (BOOL)canJump
{
    // to match the AVPlayerViewController behavior only allow jumping when playing.
    return [VLCPlaybackController sharedInstance].isPlaying;
}
- (BOOL)canScrub
{
    // to match the AVPlayerViewController behavior only allow scrubbing when paused.
    return ![VLCPlaybackController sharedInstance].isPlaying;
}

670
#pragma mark -
671 672 673 674 675

- (void)updateTimeLabelsForScrubbingFraction:(CGFloat)scrubbingFraction
{
    VLCTransportBar *bar = self.transportBar;
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
Tobias's avatar
Tobias committed
676
    // MAX 1, _ is ugly hack to prevent --:-- instead of 00:00
677
    int scrubbingTimeInt = MAX(1,vpc.mediaDuration*scrubbingFraction);
Tobias's avatar
Tobias committed
678 679
    VLCTime *scrubbingTime = [VLCTime timeWithInt:scrubbingTimeInt];
    bar.markerTimeLabel.text = [scrubbingTime stringValue];
680
    VLCTime *remainingTime = [VLCTime timeWithInt:-(int)(vpc.mediaDuration-scrubbingTime.intValue)];
Tobias's avatar
Tobias committed
681 682 683
    bar.remainingTimeLabel.text = [remainingTime stringValue];
}

684
- (void)startScrubbing
Tobias's avatar
Tobias committed
685
{
686 687
    NSAssert(self.isSeekable, @"Tried to seek while not media is not seekable.");

688
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
689 690
    self.transportBar.scrubbing = YES;
    [self updateDimmingView];
691 692 693
    if (vpc.isPlaying) {
        [vpc playPause];
    }
694 695 696 697 698
}
- (void)stopScrubbing
{
    self.transportBar.scrubbing = NO;
    [self updateDimmingView];
699 700
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
    [vpc playPause];
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
}

- (void)updateDimmingView
{
    BOOL shouldBeVisible = self.transportBar.scrubbing;
    BOOL isVisible = self.dimmingView.alpha == 1.0;
    if (shouldBeVisible != isVisible) {
        [UIView animateWithDuration:0.3 animations:^{
            self.dimmingView.alpha = shouldBeVisible ? 1.0 : 0.0;
        }];
    }
}

- (void)updateActivityIndicatorForState:(VLCMediaPlayerState)state {
    UIActivityIndicatorView *indicator = self.activityIndicator;
    switch (state) {
        case VLCMediaPlayerStateBuffering:
            if (!indicator.isAnimating) {
                self.activityIndicator.alpha = 1.0;
                [self.activityIndicator startAnimating];
            }
            break;
        default:
            if (indicator.isAnimating) {
                [self.activityIndicator stopAnimating];
                self.activityIndicator.alpha = 0.0;
            }
            break;
Tobias's avatar
Tobias committed
729 730 731
    }
}

732 733 734 735 736 737 738 739 740 741 742
#pragma mark - PlaybackControls

- (void)fireHidePlaybackControlsIfNotPlayingTimer:(NSTimer *)timer
{
    BOOL playing = [[VLCPlaybackController sharedInstance] isPlaying];
    if (playing) {
        [self animatePlaybackControlsToVisibility:NO];
    }
}
- (void)showPlaybackControlsIfNeededForUserInteraction
{
743 744 745 746
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
    NSInteger currentTitle = [vpc indexOfCurrentTitle];
    if (currentTitle < [vpc numberOfTitles]) {
        NSDictionary *title = [vpc titleDescriptionsDictAtIndex:currentTitle];
747 748 749 750 751
        if ([[title objectForKey:VLCTitleDescriptionIsMenu] boolValue]) {
            return;
        }
    }

752 753
    if (self.bottomOverlayView.alpha == 0.0) {
        [self animatePlaybackControlsToVisibility:YES];
754 755 756 757 758

        // We need an additional update here because in some cases (e.g. when the playback was
        // paused or started buffering), the transport bar is only updated when it is visible
        // and if the playback is interrupted, no updates of the transport bar are triggered.
        [self updateTransportBarPosition];
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
    }
    [self hidePlaybackControlsIfNeededAfterDelay];
}
- (void)hidePlaybackControlsIfNeededAfterDelay
{
    self.hidePlaybackControlsViewAfterDeleayTimer = [NSTimer scheduledTimerWithTimeInterval:3.0
                                                                                     target:self
                                                                                   selector:@selector(fireHidePlaybackControlsIfNotPlayingTimer:)
                                                                                   userInfo:nil repeats:NO];
}


- (void)animatePlaybackControlsToVisibility:(BOOL)visible
{
    NSTimeInterval duration = visible ? 0.3 : 1.0;

    CGFloat alpha = visible ? 1.0 : 0.0;
    [UIView animateWithDuration:duration
                     animations:^{
                         self.bottomOverlayView.alpha = alpha;
                     }];
}


#pragma mark - Properties
- (void)setHidePlaybackControlsViewAfterDeleayTimer:(NSTimer *)hidePlaybackControlsViewAfterDeleayTimer {
    [_hidePlaybackControlsViewAfterDeleayTimer invalidate];
    _hidePlaybackControlsViewAfterDeleayTimer = hidePlaybackControlsViewAfterDeleayTimer;
}

789 790 791 792 793 794 795 796
- (VLCPlaybackInfoTVViewController *)infoViewController
{
    if (!_infoViewController) {
        _infoViewController = [[VLCPlaybackInfoTVViewController alloc] initWithNibName:nil bundle:nil];
    }
    return _infoViewController;
}

797 798


799 800
#pragma mark - playback controller delegation

801 802
- (void)prepareForMediaPlayback:(VLCPlaybackController *)controller
{
803
    self.audioView.hidden = YES;
804 805
}

806
- (void)playbackDidStop
807
{
808
    [self dismissViewControllerAnimated:YES completion:nil];
809 810 811 812 813 814 815 816
}

- (void)mediaPlayerStateChanged:(VLCMediaPlayerState)currentState
                      isPlaying:(BOOL)isPlaying
currentMediaHasTrackToChooseFrom:(BOOL)currentMediaHasTrackToChooseFrom
        currentMediaHasChapters:(BOOL)currentMediaHasChapters
          forPlaybackController:(VLCPlaybackController *)controller
{
817

818
    [self updateActivityIndicatorForState:currentState];
819 820

    if (controller.isPlaying) {
821 822 823 824 825
        // we sometimes don't set the vout correctly if playback stops and restarts without dismising and redisplaying the VC
        // hence, manually reset the vout container here if it doesn't have sufficient children
        if (self.movieView.subviews.count < 2) {
            controller.videoOutputView = self.movieView;
        }
826

827 828 829 830 831
        if (!self.bufferingLabel.hidden) {
            [UIView animateWithDuration:.3 animations:^{
                self.bufferingLabel.hidden = YES;
            }];
        }
832
    }
833 834
}

835
- (void)displayMetadataForPlaybackController:(VLCPlaybackController *)controller metadata:(VLCMetaData *)metadata
836
{
837 838 839
    NSString *title = metadata.title;
    NSString *artist = metadata.artist;
    NSString *albumName = metadata.albumName;
840
    self.titleLabel.text = title;
841
    if (metadata.isAudioOnly) {
842
        self.audioArtworkImageView.image = nil;
843
        self.audioDescriptionTextView.hidden = YES;
844
        [self stopAudioDescriptionAnimation];
845

846
        if (artist != nil && albumName != nil) {
847 848
            [UIView animateWithDuration:.3 animations:^{
                self.audioArtistLabel.text = artist;
849
                self.audioArtistLabel.hidden = NO;
850
                self.audioAlbumNameLabel.text = albumName;
851
                self.audioAlbumNameLabel.hidden = NO;
852
            }];
853
            APLog(@"Audio-only track meta changed, tracing artist '%@' and album '%@'", artist, albumName);
854
        } else if (artist != nil) {
855 856
            [UIView animateWithDuration:.3 animations:^{
                self.audioArtistLabel.text = artist;
857 858
                self.audioArtistLabel.hidden = NO;
                self.audioAlbumNameLabel.hidden = YES;
859
            }];
860 861 862 863
            APLog(@"Audio-only track meta changed, tracing artist '%@'", artist);
        } else if (title != nil) {
            NSRange deviderRange = [title rangeOfString:@" - "];
            if (deviderRange.length != 0) { // for radio stations, all we have is "ARTIST - TITLE"
864 865
                artist = [title substringToIndex:deviderRange.location];
                title = [title substringFromIndex:deviderRange.location + deviderRange.length];
866
            }
867 868 869
            APLog(@"Audio-only track meta changed, tracing artist '%@'", artist);
            [UIView animateWithDuration:.3 animations:^{
                self.audioArtistLabel.text = artist;
870 871
                self.audioArtistLabel.hidden = NO;
                self.audioAlbumNameLabel.hidden = YES;
872
            }];
873
        }
874
        if (![self.lastArtist isEqualToString:artist]) {
875 876 877 878 879
            UIImage *dummyImage = [UIImage imageNamed:@"about-app-icon"];
            [UIView animateWithDuration:.3 animations:^{
                self.audioArtworkImageView.image = dummyImage;
                self.audioLargeBackgroundImageView.image = dummyImage;
            }];
880 881
        }
        self.lastArtist = artist;
882
        self.audioTitleLabel.text = title;
883
        self.audioTitleLabel.hidden = NO;
884

885 886 887
        [UIView animateWithDuration:0.3 animations:^{
            self.audioView.hidden = NO;
        }];
888 889 890 891
    } else if (!self.audioView.hidden) {
        self.audioView.hidden = YES;
        self.audioArtworkImageView.image = nil;
        [self.audioLargeBackgroundImageView stopAnimating];
892
    }
893 894
}

895 896
#pragma mark -

897
- (void)updateTransportBarPosition
898
{
899
    VLCPlaybackController *controller = [VLCPlaybackController sharedInstance];
900
    VLCTransportBar *transportBar = self.transportBar;
901 902 903
    transportBar.remainingTimeLabel.text = [[controller remainingTime] stringValue];
    transportBar.markerTimeLabel.text = [[controller playedTime] stringValue];
    transportBar.playbackFraction = controller.playbackPosition;
904 905 906 907
}

- (void)playbackPositionUpdated:(VLCPlaybackController *)controller
{
908 909
    // FIXME: hard coded state since the state in mediaPlayer is incorrectly still buffering
    [self updateActivityIndicatorForState:VLCMediaPlayerStatePlaying];
910

911
    if (self.bottomOverlayView.alpha != 0.0) {
912
        [self updateTransportBarPosition];
913
    }
914 915
}

916 917 918 919 920 921 922 923
#pragma mark - gesture recognizer delegate

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if ([gestureRecognizer.allowedPressTypes containsObject:@(UIPressTypeMenu)]) {
        return self.transportBar.scrubbing;
    }
    return YES;
}
924 925
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
926
    return [self.simultaneousGestureRecognizers containsObject:gestureRecognizer];
927
}
928

929
- (void)scrollAudioDescriptionAnimationToTop
930
{
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
    [self stopAudioDescriptionAnimation];
    [self.audioDescriptionTextView setContentOffset:CGPointZero animated:YES];
    [self startAudioDescriptionAnimation];
}

- (void)startAudioDescriptionAnimation
{
    [self.audioDescriptionScrollTimer invalidate];
    self.audioDescriptionScrollTimer = [NSTimer scheduledTimerWithTimeInterval:2.0
                                                                        target:self
                                                                      selector:@selector(animateAudioDescription)
                                                                      userInfo:nil repeats:NO];
}

- (void)stopAudioDescriptionAnimation
{
    [self.audioDescriptionScrollTimer invalidate];
    self.audioDescriptionScrollTimer = nil;
    [self.displayLink invalidate];
    self.displayLink = nil;
}

- (void)animateAudioDescription
{
    [self.displayLink invalidate];
    self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkTriggered:)];
    [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}

- (void)displayLinkTriggered:(CADisplayLink*)link
{
    UIScrollView *scrollView = self.audioDescriptionTextView;
    CGFloat viewHeight = CGRectGetHeight(scrollView.frame);
    CGFloat maxOffsetY = scrollView.contentSize.height - viewHeight;

966
    CFTimeInterval secondsPerPage = 8.0;
967 968 969 970 971 972 973 974 975
    CGFloat offset = link.duration/secondsPerPage * viewHeight;

    CGFloat newYOffset = scrollView.contentOffset.y + offset;

    if (newYOffset > maxOffsetY+viewHeight) {
        scrollView.contentOffset = CGPointMake(0, -viewHeight);
    } else {
        scrollView.contentOffset = CGPointMake(0, newYOffset);
    }
976 977
}

978
@end
979 980 981 982 983 984 985 986 987 988 989 990 991


@implementation VLCFullscreenMovieTVViewController (UIViewControllerTransitioningDelegate)

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    return [[VLCPlaybackInfoTVTransitioningAnimator alloc] init];
}
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    return [[VLCPlaybackInfoTVTransitioningAnimator alloc] init];
}
@end