IJKFFMoviePlayerController.m 51.3 KB
Newer Older
Z
Zhang Rui 已提交
1
/*
Z
Zhang Rui 已提交
2
 * IJKFFMoviePlayerController.m
Z
Zhang Rui 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * Copyright (c) 2013 Zhang Rui <bbcallen@gmail.com>
 *
 * This file is part of ijkPlayer.
 *
 * ijkPlayer is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * ijkPlayer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with ijkPlayer; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */
22

Z
Zhang Rui 已提交
23
#import "IJKFFMoviePlayerController.h"
Z
Zhang Rui 已提交
24 25

#import <UIKit/UIKit.h>
Z
Zhang Rui 已提交
26
#import "IJKFFMoviePlayerDef.h"
27
#import "IJKMediaPlayback.h"
28
#import "IJKMediaModule.h"
29
#import "IJKAudioKit.h"
30
#import "IJKNotificationManager.h"
Z
Zhang Rui 已提交
31
#import "NSString+IJKMedia.h"
32

33 34
#include "string.h"

X
k0.7.0  
Xinzheng Zhang 已提交
35
static const char *kIJKFFRequiredFFmpegVersion = "ff3.2--ijk0.7.0--20161102--001"
Z
Zhang Rui 已提交
36

37 38 39 40 41 42 43 44
// It means you didn't call shutdown if you found this object leaked.
@interface IJKWeakHolder : NSObject
@property (nonatomic, weak) id object;
@end

@implementation IJKWeakHolder
@end

45
@interface IJKFFMoviePlayerController()
Z
Zhang Rui 已提交
46

47
@end
48

Z
Zhang Rui 已提交
49
@implementation IJKFFMoviePlayerController {
50
    IjkMediaPlayer *_mediaPlayer;
Z
Zhang Rui 已提交
51
    IJKSDLGLView *_glView;
Z
Zhang Rui 已提交
52
    IJKFFMoviePlayerMessagePool *_msgPool;
Z
Zhang Rui 已提交
53
    NSString *_urlString;
54 55 56 57 58

    NSInteger _videoWidth;
    NSInteger _videoHeight;
    NSInteger _sampleAspectRatioNumerator;
    NSInteger _sampleAspectRatioDenominator;
59

B
bbcallen 已提交
60
    BOOL      _seeking;
61
    NSInteger _bufferingTime;
Z
Zhang Rui 已提交
62
    NSInteger _bufferingPosition;
63 64

    BOOL _keepScreenOnWhilePlaying;
Z
Zhang Rui 已提交
65
    BOOL _pauseInBackground;
Z
Zhang Rui 已提交
66
    BOOL _isVideoToolboxOpen;
67
    BOOL _playingBeforeInterruption;
68 69

    IJKNotificationManager *_notificationManager;
Z
Zhang Rui 已提交
70

71
    AVAppAsyncStatistic _asyncStat;
Z
Zhang Rui 已提交
72 73
    BOOL _shouldShowHudView;
    NSTimer *_hudTimer;
74 75
}

Z
Zhang Rui 已提交
76
@synthesize view = _view;
77 78 79
@synthesize currentPlaybackTime;
@synthesize duration;
@synthesize playableDuration;
Z
Zhang Rui 已提交
80
@synthesize bufferingProgress = _bufferingProgress;
81

Y
Yuvesy 已提交
82 83
@synthesize numberOfBytesTransferred = _numberOfBytesTransferred;

B
bbcallen 已提交
84
@synthesize isPreparedToPlay = _isPreparedToPlay;
B
bbcallen 已提交
85
@synthesize playbackState = _playbackState;
86
@synthesize loadState = _loadState;
87

88
@synthesize naturalSize = _naturalSize;
89 90 91
@synthesize scalingMode = _scalingMode;
@synthesize shouldAutoplay = _shouldAutoplay;

Y
airplay  
yuvesy@yuvesy.com 已提交
92 93 94 95 96
@synthesize allowsMediaAirPlay = _allowsMediaAirPlay;
@synthesize airPlayMediaActive = _airPlayMediaActive;

@synthesize isDanmakuMediaAirPlay = _isDanmakuMediaAirPlay;

Z
Zhang Rui 已提交
97 98
@synthesize monitor = _monitor;

99 100 101
#define FFP_IO_STAT_STEP (50 * 1024)

// as an example
102
void IJKFFIOStatDebugCallback(const char *url, int type, int bytes)
103 104 105 106 107 108 109 110 111
{
    static int64_t s_ff_io_stat_check_points = 0;
    static int64_t s_ff_io_stat_bytes = 0;
    if (!url)
        return;

    if (type != IJKMP_IO_STAT_READ)
        return;

Z
Zhang Rui 已提交
112
    if (!av_strstart(url, "http:", NULL))
113 114 115 116 117 118
        return;

    s_ff_io_stat_bytes += bytes;
    if (s_ff_io_stat_bytes < s_ff_io_stat_check_points ||
        s_ff_io_stat_bytes > s_ff_io_stat_check_points + FFP_IO_STAT_STEP) {
        s_ff_io_stat_check_points = s_ff_io_stat_bytes;
Z
Zhang Rui 已提交
119
        NSLog(@"io-stat: %s, +%d = %"PRId64"\n", url, bytes, s_ff_io_stat_bytes);
120 121 122 123 124
    }
}

void IJKFFIOStatRegister(void (*cb)(const char *url, int type, int bytes))
{
125
    ijkmp_io_stat_register(cb);
126 127
}

Z
Zhang Rui 已提交
128 129 130
void IJKFFIOStatCompleteDebugCallback(const char *url,
                                      int64_t read_bytes, int64_t total_size,
                                      int64_t elpased_time, int64_t total_duration)
Z
Zhang Rui 已提交
131 132 133 134 135 136 137
{
    if (!url)
        return;

    if (!av_strstart(url, "http:", NULL))
        return;

Z
Zhang Rui 已提交
138 139
    NSLog(@"io-stat-complete: %s, %"PRId64"/%"PRId64", %"PRId64"/%"PRId64"\n",
          url, read_bytes, total_size, elpased_time, total_duration);
Z
Zhang Rui 已提交
140 141
}

Z
Zhang Rui 已提交
142 143 144
void IJKFFIOStatCompleteRegister(void (*cb)(const char *url,
                                            int64_t read_bytes, int64_t total_size,
                                            int64_t elpased_time, int64_t total_duration))
Z
Zhang Rui 已提交
145 146 147 148
{
    ijkmp_io_stat_complete_register(cb);
}

149 150
- (id)initWithContentURL:(NSURL *)aUrl
             withOptions:(IJKFFOptions *)options
151
{
B
bbcallen 已提交
152 153 154
    if (aUrl == nil)
        return nil;

155 156 157 158
    // Detect if URL is file path and return proper string for it
    NSString *aUrlString = [aUrl isFileURL] ? [aUrl path] : [aUrl absoluteString];

    return [self initWithContentURLString:aUrlString
Z
Zhang Rui 已提交
159
                              withOptions:options];
160 161 162 163 164 165 166 167
}

- (id)initWithContentURLString:(NSString *)aUrlString
                   withOptions:(IJKFFOptions *)options
{
    if (aUrlString == nil)
        return nil;

168 169
    self = [super init];
    if (self) {
Z
Zhang Rui 已提交
170
        ijkmp_global_init();
Z
Zhang Rui 已提交
171
        ijkmp_global_set_inject_callback(ijkff_inject_callback);
Z
Zhang Rui 已提交
172

Z
Zhang Rui 已提交
173 174
        [IJKFFMoviePlayerController checkIfFFmpegVersionMatch:NO];

175 176 177
        if (options == nil)
            options = [IJKFFOptions optionsByDefault];

Z
Zhang Rui 已提交
178 179 180
        // IJKFFIOStatRegister(IJKFFIOStatDebugCallback);
        // IJKFFIOStatCompleteRegister(IJKFFIOStatCompleteDebugCallback);

181
        // init fields
182
        _scalingMode = IJKMPMovieScalingModeAspectFit;
183
        _shouldAutoplay = YES;
Z
Zhang Rui 已提交
184
        memset(&_asyncStat, 0, sizeof(_asyncStat));
185

Z
Zhang Rui 已提交
186 187
        _monitor = [[IJKFFMonitor alloc] init];

188
        // init media resource
Z
Zhang Rui 已提交
189
        _urlString = aUrlString;
190

191
        // init player
Z
Zhang Rui 已提交
192
        _mediaPlayer = ijkmp_ios_create(media_player_msg_loop);
Z
Zhang Rui 已提交
193
        _msgPool = [[IJKFFMoviePlayerMessagePool alloc] init];
194 195
        IJKWeakHolder *weakHolder = [IJKWeakHolder new];
        weakHolder.object = self;
Z
Zhang Rui 已提交
196

Z
Zhang Rui 已提交
197
        ijkmp_set_weak_thiz(_mediaPlayer, (__bridge_retained void *) self);
198
        ijkmp_set_inject_opaque(_mediaPlayer, (__bridge_retained void *) weakHolder);
Z
Zhang Rui 已提交
199
        ijkmp_set_option_int(_mediaPlayer, IJKMP_OPT_CATEGORY_PLAYER, "start-on-prepared", _shouldAutoplay ? 1 : 0);
Z
Zhang Rui 已提交
200

201
        // init video sink
Z
Zhang Rui 已提交
202
        _glView = [[IJKSDLGLView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
203
        _glView.shouldShowHudView = NO;
Z
Zhang Rui 已提交
204
        _view   = _glView;
Z
Zhang Rui 已提交
205 206 207 208
        [_glView setHudValue:nil forKey:@"scheme"];
        [_glView setHudValue:nil forKey:@"host"];
        [_glView setHudValue:nil forKey:@"path"];
        [_glView setHudValue:nil forKey:@"ip"];
209
        [_glView setHudValue:nil forKey:@"tcp-info"];
Z
Zhang Rui 已提交
210 211
        [_glView setHudValue:nil forKey:@"http"];
        [_glView setHudValue:nil forKey:@"tcp-spd"];
Z
Zhang Rui 已提交
212 213 214 215 216
        [_glView setHudValue:nil forKey:@"t-prepared"];
        [_glView setHudValue:nil forKey:@"t-render"];
        [_glView setHudValue:nil forKey:@"t-preroll"];
        [_glView setHudValue:nil forKey:@"t-http-open"];
        [_glView setHudValue:nil forKey:@"t-http-seek"];
217 218
        
        self.shouldShowHudView = options.showHudView;
Z
Zhang Rui 已提交
219

Z
Zhang Rui 已提交
220
        ijkmp_ios_set_glview(_mediaPlayer, _glView);
221
        ijkmp_set_option(_mediaPlayer, IJKMP_OPT_CATEGORY_PLAYER, "overlay-format", "fcc-_es2");
Z
Zhang Rui 已提交
222 223 224 225 226
#ifdef DEBUG
        [IJKFFMoviePlayerController setLogLevel:k_IJK_LOG_DEBUG];
#else
        [IJKFFMoviePlayerController setLogLevel:k_IJK_LOG_SILENT];
#endif
227
        // init audio sink
228
        [[IJKAudioKit sharedInstance] setupAudioSession];
229

230
        [options applyTo:_mediaPlayer];
231
        _pauseInBackground = NO;
232

233
        // init extra
234 235
        _keepScreenOnWhilePlaying = YES;
        [self setScreenOn:YES];
236

237
        _notificationManager = [[IJKNotificationManager alloc] init];
238
        [self registerApplicationObservers];
239 240 241 242
    }
    return self;
}

243 244
- (void)setScreenOn: (BOOL)on
{
245 246
    [IJKMediaModule sharedModule].mediaModuleIdleTimerDisabled = on;
    // [UIApplication sharedApplication].idleTimerDisabled = on;
247 248
}

249 250
- (void)dealloc
{
251
//    [self unregisterApplicationObservers];
252 253
}

254 255 256 257 258 259 260
- (void)setShouldAutoplay:(BOOL)shouldAutoplay
{
    _shouldAutoplay = shouldAutoplay;

    if (!_mediaPlayer)
        return;

Z
Zhang Rui 已提交
261
    ijkmp_set_option_int(_mediaPlayer, IJKMP_OPT_CATEGORY_PLAYER, "start-on-prepared", _shouldAutoplay ? 1 : 0);
262 263 264 265 266 267 268
}

- (BOOL)shouldAutoplay
{
    return _shouldAutoplay;
}

269 270
- (void)prepareToPlay
{
Z
Zhang Rui 已提交
271 272 273
    if (!_mediaPlayer)
        return;

274 275
    [self setScreenOn:_keepScreenOnWhilePlaying];

Z
Zhang Rui 已提交
276
    ijkmp_set_data_source(_mediaPlayer, [_urlString UTF8String]);
Z
Zhang Rui 已提交
277
    ijkmp_set_option(_mediaPlayer, IJKMP_OPT_CATEGORY_FORMAT, "safe", "0"); // for concat demuxer
Z
Zhang Rui 已提交
278 279

    _monitor.prepareStartTick = (int64_t)SDL_GetTickHR();
Z
Zhang Rui 已提交
280
    ijkmp_prepare_async(_mediaPlayer);
281 282
}

Z
Zhang Rui 已提交
283 284 285 286 287 288 289 290 291 292 293 294 295 296
- (void)setHudUrl:(NSString *)urlString
{
    if ([[NSThread currentThread] isMainThread]) {
        NSURL *url = [NSURL URLWithString:urlString];
        [_glView setHudValue:url.scheme forKey:@"scheme"];
        [_glView setHudValue:url.host   forKey:@"host"];
        [_glView setHudValue:url.path   forKey:@"path"];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self setHudUrl:urlString];
        });
    }
}

297 298
- (void)play
{
Z
Zhang Rui 已提交
299 300
    if (!_mediaPlayer)
        return;
301

302 303
    [self setScreenOn:_keepScreenOnWhilePlaying];

Z
Zhang Rui 已提交
304
    [self startHudTimer];
Z
Zhang Rui 已提交
305
    ijkmp_start(_mediaPlayer);
306 307 308 309
}

- (void)pause
{
Z
Zhang Rui 已提交
310 311
    if (!_mediaPlayer)
        return;
312

313
//    [self stopHudTimer];
Z
Zhang Rui 已提交
314
    ijkmp_pause(_mediaPlayer);
315 316 317 318
}

- (void)stop
{
Z
Zhang Rui 已提交
319 320
    if (!_mediaPlayer)
        return;
321

322
    [self setScreenOn:NO];
323

Z
Zhang Rui 已提交
324
    [self stopHudTimer];
Z
Zhang Rui 已提交
325
    ijkmp_stop(_mediaPlayer);
326 327 328 329
}

- (BOOL)isPlaying
{
Z
Zhang Rui 已提交
330 331 332 333 334 335
    if (!_mediaPlayer)
        return NO;

    return ijkmp_is_playing(_mediaPlayer);
}

Z
Zhang Rui 已提交
336 337 338 339 340
- (void)setPauseInBackground:(BOOL)pause
{
    _pauseInBackground = pause;
}

Z
Zhang Rui 已提交
341 342 343 344 345
- (BOOL)isVideoToolboxOpen
{
    if (!_mediaPlayer)
        return NO;

346
    return _isVideoToolboxOpen;
Z
Zhang Rui 已提交
347 348
}

Z
Zhang Rui 已提交
349
inline static int getPlayerOption(IJKFFOptionCategory category)
350
{
Z
Zhang Rui 已提交
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
    int mp_category = -1;
    switch (category) {
        case kIJKFFOptionCategoryFormat:
            mp_category = IJKMP_OPT_CATEGORY_FORMAT;
            break;
        case kIJKFFOptionCategoryCodec:
            mp_category = IJKMP_OPT_CATEGORY_CODEC;
            break;
        case kIJKFFOptionCategorySws:
            mp_category = IJKMP_OPT_CATEGORY_SWS;
            break;
        case kIJKFFOptionCategoryPlayer:
            mp_category = IJKMP_OPT_CATEGORY_PLAYER;
            break;
        default:
            NSLog(@"unknown option category: %d\n", category);
    }
    return mp_category;
}

- (void)setOptionValue:(NSString *)value
                forKey:(NSString *)key
            ofCategory:(IJKFFOptionCategory)category
{
    assert(_mediaPlayer);
    if (!_mediaPlayer)
        return;

    ijkmp_set_option(_mediaPlayer, getPlayerOption(category), [key UTF8String], [value UTF8String]);
}

Z
Zhang Rui 已提交
382
- (void)setOptionIntValue:(int64_t)value
Z
Zhang Rui 已提交
383 384 385 386
                   forKey:(NSString *)key
               ofCategory:(IJKFFOptionCategory)category
{
    assert(_mediaPlayer);
387 388 389
    if (!_mediaPlayer)
        return;

Z
Zhang Rui 已提交
390
    ijkmp_set_option_int(_mediaPlayer, getPlayerOption(category), [key UTF8String], value);
391 392
}

393
+ (void)setLogReport:(BOOL)preferLogReport
394
{
395
    ijkmp_global_set_log_report(preferLogReport ? 1 : 0);
396 397
}

398
+ (void)setLogLevel:(IJKLogLevel)logLevel
Z
Zhang Rui 已提交
399
{
400
    ijkmp_global_set_log_level(logLevel);
Z
Zhang Rui 已提交
401 402
}

Z
Zhang Rui 已提交
403 404
+ (BOOL)checkIfFFmpegVersionMatch:(BOOL)showAlert;
{
405 406 407
    const char *actualVersion = av_version_info();
    const char *expectVersion = kIJKFFRequiredFFmpegVersion;
    if (0 == strcmp(actualVersion, expectVersion)) {
Z
Zhang Rui 已提交
408 409
        return YES;
    } else {
Z
Zhang Rui 已提交
410 411
        NSString *message = [NSString stringWithFormat:@"actual: %s\n expect: %s\n", actualVersion, expectVersion];
        NSLog(@"\n!!!!!!!!!!\n%@\n!!!!!!!!!!\n", message);
Z
Zhang Rui 已提交
412 413 414 415 416 417 418 419 420 421 422 423
        if (showAlert) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Unexpected FFmpeg version"
                                                                message:message
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
            [alertView show];
        }
        return NO;
    }
}

424
+ (BOOL)checkIfPlayerVersionMatch:(BOOL)showAlert
425
                          version:(NSString *)version
426
{
427 428 429
    const char *actualVersion = ijkmp_version();
    const char *expectVersion = version.UTF8String;
    if (0 == strcmp(actualVersion, expectVersion)) {
430 431 432
        return YES;
    } else {
        if (showAlert) {
433 434
            NSString *message = [NSString stringWithFormat:@"actual: %s\n expect: %s\n",
                                 actualVersion, expectVersion];
435 436 437 438 439 440 441 442 443 444 445
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Unexpected ijkplayer version"
                                                                message:message
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
            [alertView show];
        }
        return NO;
    }
}

446
- (void)shutdown
B
bbcallen 已提交
447 448 449
{
    if (!_mediaPlayer)
        return;
Z
Zhang Rui 已提交
450 451

    [self stopHudTimer];
452
    [self unregisterApplicationObservers];
453
    [self setScreenOn:NO];
454

455
    [self performSelectorInBackground:@selector(shutdownWaitStop:) withObject:self];
B
bbcallen 已提交
456 457
}

458
- (void)shutdownWaitStop:(IJKFFMoviePlayerController *) mySelf
B
bbcallen 已提交
459 460 461 462 463
{
    if (!_mediaPlayer)
        return;

    ijkmp_stop(_mediaPlayer);
Z
Zhang Rui 已提交
464
    ijkmp_shutdown(_mediaPlayer);
Z
Zhang Rui 已提交
465

466
    [self performSelectorOnMainThread:@selector(shutdownClose:) withObject:self waitUntilDone:YES];
B
bbcallen 已提交
467 468
}

469
- (void)shutdownClose:(IJKFFMoviePlayerController *) mySelf
470 471 472 473
{
    if (!_mediaPlayer)
        return;

Z
Zhang Rui 已提交
474 475 476 477
    _segmentOpenDelegate    = nil;
    _tcpOpenDelegate        = nil;
    _httpOpenDelegate       = nil;
    _liveOpenDelegate       = nil;
Z
Zhang Rui 已提交
478
    _nativeInvokeDelegate   = nil;
Z
Zhang Rui 已提交
479

480
    __unused id weakHolder = (__bridge_transfer IJKWeakHolder*)ijkmp_set_inject_opaque(_mediaPlayer, NULL);
B
bbcallen 已提交
481
    ijkmp_dec_ref_p(&_mediaPlayer);
Z
Zhang Rui 已提交
482 483 484 485 486 487

    [self didShutdown];
}

- (void)didShutdown
{
488 489
}

490
- (IJKMPMoviePlaybackState)playbackState
B
bbcallen 已提交
491 492 493 494
{
    if (!_mediaPlayer)
        return NO;

495
    IJKMPMoviePlaybackState mpState = IJKMPMoviePlaybackStateStopped;
B
bbcallen 已提交
496 497 498 499 500 501
    int state = ijkmp_get_state(_mediaPlayer);
    switch (state) {
        case MP_STATE_STOPPED:
        case MP_STATE_COMPLETED:
        case MP_STATE_ERROR:
        case MP_STATE_END:
502
            mpState = IJKMPMoviePlaybackStateStopped;
B
bbcallen 已提交
503 504 505 506 507
            break;
        case MP_STATE_IDLE:
        case MP_STATE_INITIALIZED:
        case MP_STATE_ASYNC_PREPARING:
        case MP_STATE_PAUSED:
508
            mpState = IJKMPMoviePlaybackStatePaused;
B
bbcallen 已提交
509
            break;
Z
Zhang Rui 已提交
510
        case MP_STATE_PREPARED:
B
bbcallen 已提交
511 512
        case MP_STATE_STARTED: {
            if (_seeking)
513
                mpState = IJKMPMoviePlaybackStateSeekingForward;
B
bbcallen 已提交
514
            else
515
                mpState = IJKMPMoviePlaybackStatePlaying;
B
bbcallen 已提交
516
            break;
B
bbcallen 已提交
517
        }
B
bbcallen 已提交
518
    }
519 520 521 522 523 524
    // IJKMPMoviePlaybackStatePlaying,
    // IJKMPMoviePlaybackStatePaused,
    // IJKMPMoviePlaybackStateStopped,
    // IJKMPMoviePlaybackStateInterrupted,
    // IJKMPMoviePlaybackStateSeekingForward,
    // IJKMPMoviePlaybackStateSeekingBackward
B
bbcallen 已提交
525
    return mpState;
B
bbcallen 已提交
526 527
}

Z
Zhang Rui 已提交
528 529 530 531 532
- (void)setCurrentPlaybackTime:(NSTimeInterval)aCurrentPlaybackTime
{
    if (!_mediaPlayer)
        return;

B
bbcallen 已提交
533 534
    _seeking = YES;
    [[NSNotificationCenter defaultCenter]
535
     postNotificationName:IJKMPMoviePlayerPlaybackStateDidChangeNotification
B
bbcallen 已提交
536 537
     object:self];

538
    _bufferingPosition = 0;
539
    ijkmp_seek_to(_mediaPlayer, aCurrentPlaybackTime * 1000);
Z
Zhang Rui 已提交
540 541
}

542
- (NSTimeInterval)currentPlaybackTime
Z
Zhang Rui 已提交
543 544 545 546
{
    if (!_mediaPlayer)
        return 0.0f;

547
    NSTimeInterval ret = ijkmp_get_current_position(_mediaPlayer);
Z
Zhang Rui 已提交
548 549 550
    if (isnan(ret) || isinf(ret))
        return -1;

551
    return ret / 1000;
Z
Zhang Rui 已提交
552 553
}

554
- (NSTimeInterval)duration
Z
Zhang Rui 已提交
555 556 557 558
{
    if (!_mediaPlayer)
        return 0.0f;

559
    NSTimeInterval ret = ijkmp_get_duration(_mediaPlayer);
Z
Zhang Rui 已提交
560 561 562
    if (isnan(ret) || isinf(ret))
        return -1;

563
    return ret / 1000;
564
}
565

566 567
- (NSTimeInterval)playableDuration
{
568 569 570
    if (!_mediaPlayer)
        return 0.0f;

Z
Zhang Rui 已提交
571 572 573 574 575 576 577 578 579 580 581 582
    NSTimeInterval demux_cache = ((NSTimeInterval)ijkmp_get_playable_duration(_mediaPlayer)) / 1000;

    int64_t buf_forwards = _asyncStat.buf_forwards;
    if (buf_forwards > 0) {
        int64_t bit_rate = ijkmp_get_property_int64(_mediaPlayer, FFP_PROP_INT64_BIT_RATE, 0);
        if (bit_rate > 0) {
            NSTimeInterval io_cache = ((float)buf_forwards) * 8 / bit_rate;
            return io_cache + demux_cache;
        }
    }

    return demux_cache;
583 584
}

585 586 587 588 589 590 591 592 593 594 595 596 597 598
- (CGSize)naturalSize
{
    return _naturalSize;
}

- (void)changeNaturalSize
{
    [self willChangeValueForKey:@"naturalSize"];
    if (_sampleAspectRatioNumerator > 0 && _sampleAspectRatioDenominator > 0) {
        self->_naturalSize = CGSizeMake(1.0f * _videoWidth * _sampleAspectRatioNumerator / _sampleAspectRatioDenominator, _videoHeight);
    } else {
        self->_naturalSize = CGSizeMake(_videoWidth, _videoHeight);
    }
    [self didChangeValueForKey:@"naturalSize"];
Z
Zhang Rui 已提交
599 600 601 602 603 604

    if (self->_naturalSize.width > 0 && self->_naturalSize.height > 0) {
        [[NSNotificationCenter defaultCenter]
         postNotificationName:IJKMPMovieNaturalSizeAvailableNotification
         object:self];
    }
605 606
}

607
- (void)setScalingMode: (IJKMPMovieScalingMode) aScalingMode
B
bbcallen 已提交
608
{
609
    IJKMPMovieScalingMode newScalingMode = aScalingMode;
B
bbcallen 已提交
610
    switch (aScalingMode) {
611
        case IJKMPMovieScalingModeNone:
B
bbcallen 已提交
612 613
            [_view setContentMode:UIViewContentModeCenter];
            break;
614
        case IJKMPMovieScalingModeAspectFit:
B
bbcallen 已提交
615 616
            [_view setContentMode:UIViewContentModeScaleAspectFit];
            break;
617
        case IJKMPMovieScalingModeAspectFill:
B
bbcallen 已提交
618 619
            [_view setContentMode:UIViewContentModeScaleAspectFill];
            break;
620
        case IJKMPMovieScalingModeFill:
B
bbcallen 已提交
621 622 623 624 625 626 627 628 629
            [_view setContentMode:UIViewContentModeScaleToFill];
            break;
        default:
            newScalingMode = _scalingMode;
    }

    _scalingMode = newScalingMode;
}

630
// deprecated, for MPMoviePlayerController compatiable
631
- (UIImage *)thumbnailImageAtTime:(NSTimeInterval)playbackTime timeOption:(IJKMPMovieTimeOption)option
632 633 634 635
{
    return nil;
}

Z
Zhang Rui 已提交
636 637 638 639 640 641 642 643 644 645
- (UIImage *)thumbnailImageAtCurrentTime
{
    if ([_view isKindOfClass:[IJKSDLGLView class]]) {
        IJKSDLGLView *glView = (IJKSDLGLView *)_view;
        return [glView snapshot];
    }

    return nil;
}

Z
Zhang Rui 已提交
646 647 648 649 650
- (CGFloat)fpsAtOutput
{
    return _glView.fps;
}

Z
Zhang Rui 已提交
651
inline static NSString *formatedDurationMilli(int64_t duration) {
Z
Zhang Rui 已提交
652 653 654
    if (duration >=  1000) {
        return [NSString stringWithFormat:@"%.2f sec", ((float)duration) / 1000];
    } else {
Z
Zhang Rui 已提交
655
        return [NSString stringWithFormat:@"%ld msec", (long)duration];
Z
Zhang Rui 已提交
656 657 658
    }
}

Z
Zhang Rui 已提交
659 660 661 662 663 664 665
inline static NSString *formatedDurationBytesAndBitrate(int64_t bytes, int64_t bitRate) {
    if (bitRate <= 0) {
        return @"inf";
    }
    return formatedDurationMilli(((float)bytes) * 8 * 1000 / bitRate);
}

Z
Zhang Rui 已提交
666 667 668 669 670 671 672 673 674 675
inline static NSString *formatedSize(int64_t bytes) {
    if (bytes >= 100 * 1000) {
        return [NSString stringWithFormat:@"%.2f MB", ((float)bytes) / 1000 / 1000];
    } else if (bytes >= 100) {
        return [NSString stringWithFormat:@"%.1f KB", ((float)bytes) / 1000];
    } else {
        return [NSString stringWithFormat:@"%ld B", (long)bytes];
    }
}

Z
Zhang Rui 已提交
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
inline static NSString *formatedSpeed(int64_t bytes, int64_t elapsed_milli) {
    if (elapsed_milli <= 0) {
        return @"N/A";
    }

    if (bytes <= 0) {
        return @"0";
    }

    float bytes_per_sec = ((float)bytes) * 1000.f /  elapsed_milli;
    if (bytes_per_sec >= 1000 * 1000) {
        return [NSString stringWithFormat:@"%.2f MB/s", ((float)bytes_per_sec) / 1000 / 1000];
    } else if (bytes_per_sec >= 1000) {
        return [NSString stringWithFormat:@"%.1f KB/s", ((float)bytes_per_sec) / 1000];
    } else {
        return [NSString stringWithFormat:@"%ld B/s", (long)bytes_per_sec];
    }
}

Z
Zhang Rui 已提交
695 696 697 698 699 700 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
- (void)refreshHudView
{
    if (_mediaPlayer == nil)
        return;

    int64_t vdec = ijkmp_get_property_int64(_mediaPlayer, FFP_PROP_INT64_VIDEO_DECODER, FFP_PROPV_DECODER_UNKNOWN);
    float   vdps = ijkmp_get_property_float(_mediaPlayer, FFP_PROP_FLOAT_VIDEO_DECODE_FRAMES_PER_SECOND, .0f);
    float   vfps = ijkmp_get_property_float(_mediaPlayer, FFP_PROP_FLOAT_VIDEO_OUTPUT_FRAMES_PER_SECOND, .0f);

    switch (vdec) {
        case FFP_PROPV_DECODER_VIDEOTOOLBOX:
            [_glView setHudValue:@"VideoToolbox" forKey:@"vdec"];
            break;
        case FFP_PROPV_DECODER_AVCODEC:
            [_glView setHudValue:[NSString stringWithFormat:@"avcodec %d.%d.%d",
                                  LIBAVCODEC_VERSION_MAJOR,
                                  LIBAVCODEC_VERSION_MINOR,
                                  LIBAVCODEC_VERSION_MICRO]
                          forKey:@"vdec"];
            break;
        default:
            [_glView setHudValue:@"N/A" forKey:@"vdec"];
            break;
    }

    [_glView setHudValue:[NSString stringWithFormat:@"%.2f / %.2f", vdps, vfps] forKey:@"fps"];

    int64_t vcacheb = ijkmp_get_property_int64(_mediaPlayer, FFP_PROP_INT64_VIDEO_CACHED_BYTES, 0);
    int64_t acacheb = ijkmp_get_property_int64(_mediaPlayer, FFP_PROP_INT64_AUDIO_CACHED_BYTES, 0);
    int64_t vcached = ijkmp_get_property_int64(_mediaPlayer, FFP_PROP_INT64_VIDEO_CACHED_DURATION, 0);
    int64_t acached = ijkmp_get_property_int64(_mediaPlayer, FFP_PROP_INT64_AUDIO_CACHED_DURATION, 0);
    int64_t vcachep = ijkmp_get_property_int64(_mediaPlayer, FFP_PROP_INT64_VIDEO_CACHED_PACKETS, 0);
    int64_t acachep = ijkmp_get_property_int64(_mediaPlayer, FFP_PROP_INT64_AUDIO_CACHED_PACKETS, 0);
Z
Zhang Rui 已提交
728 729 730 731
    [_glView setHudValue:[NSString stringWithFormat:@"%@, %@, %"PRId64" packets",
                          formatedDurationMilli(vcached),
                          formatedSize(vcacheb),
                          vcachep]
Z
Zhang Rui 已提交
732
                  forKey:@"v-cache"];
Z
Zhang Rui 已提交
733 734 735 736
    [_glView setHudValue:[NSString stringWithFormat:@"%@, %@, %"PRId64" packets",
                          formatedDurationMilli(acached),
                          formatedSize(acacheb),
                          acachep]
Z
Zhang Rui 已提交
737 738 739 740 741
                  forKey:@"a-cache"];

    float avdelay = ijkmp_get_property_float(_mediaPlayer, FFP_PROP_FLOAT_AVDELAY, .0f);
    float avdiff  = ijkmp_get_property_float(_mediaPlayer, FFP_PROP_FLOAT_AVDIFF, .0f);
    [_glView setHudValue:[NSString stringWithFormat:@"%.3f %.3f", avdelay, -avdiff] forKey:@"delay"];
Z
Zhang Rui 已提交
742

Z
Zhang Rui 已提交
743
    int64_t bitRate = ijkmp_get_property_int64(_mediaPlayer, FFP_PROP_INT64_BIT_RATE, 0);
Z
Zhang Rui 已提交
744 745
    [_glView setHudValue:[NSString stringWithFormat:@"-%@, %@",
                          formatedSize(_asyncStat.buf_backwards),
Z
Zhang Rui 已提交
746
                          formatedDurationBytesAndBitrate(_asyncStat.buf_backwards, bitRate)]
Z
Zhang Rui 已提交
747 748 749
                  forKey:@"async-backward"];
    [_glView setHudValue:[NSString stringWithFormat:@"+%@, %@",
                          formatedSize(_asyncStat.buf_forwards),
Z
Zhang Rui 已提交
750
                          formatedDurationBytesAndBitrate(_asyncStat.buf_forwards, bitRate)]
Z
Zhang Rui 已提交
751
                  forKey:@"async-forward"];
Z
Zhang Rui 已提交
752

Z
Zhang Rui 已提交
753 754 755
    int64_t tcpSpeed = ijkmp_get_property_int64(_mediaPlayer, FFP_PROP_INT64_TCP_SPEED, 0);
    [_glView setHudValue:[NSString stringWithFormat:@"%@", formatedSpeed(tcpSpeed, 1000)]
                  forKey:@"tcp-spd"];
Z
Zhang Rui 已提交
756 757 758 759 760 761 762 763 764 765 766 767

    [_glView setHudValue:formatedDurationMilli(_monitor.prepareDuration) forKey:@"t-prepared"];
    [_glView setHudValue:formatedDurationMilli(_monitor.firstVideoFrameLatency) forKey:@"t-render"];
    [_glView setHudValue:formatedDurationMilli(_monitor.lastPrerollDuration) forKey:@"t-preroll"];
    [_glView setHudValue:[NSString stringWithFormat:@"%@ / %d",
                          formatedDurationMilli(_monitor.lastHttpOpenDuration),
                          _monitor.httpOpenCount]
                  forKey:@"t-http-open"];
    [_glView setHudValue:[NSString stringWithFormat:@"%@ / %d",
                          formatedDurationMilli(_monitor.lastHttpSeekDuration),
                          _monitor.httpSeekCount]
                  forKey:@"t-http-seek"];
Z
Zhang Rui 已提交
768 769 770 771 772 773 774 775 776 777 778
}

- (void)startHudTimer
{
    if (!_shouldShowHudView)
        return;

    if (_hudTimer != nil)
        return;

    if ([[NSThread currentThread] isMainThread]) {
779
        _glView.shouldShowHudView = YES;
Z
Zhang Rui 已提交
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
        _hudTimer = [NSTimer scheduledTimerWithTimeInterval:.5f
                                                     target:self
                                                   selector:@selector(refreshHudView)
                                                   userInfo:nil
                                                    repeats:YES];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self startHudTimer];
        });
    }
}

- (void)stopHudTimer
{
    if (_hudTimer == nil)
        return;

    if ([[NSThread currentThread] isMainThread]) {
798
        _glView.shouldShowHudView = NO;
Z
Zhang Rui 已提交
799 800 801 802 803 804 805 806 807 808 809
        [_hudTimer invalidate];
        _hudTimer = nil;
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self stopHudTimer];
        });
    }
}

- (void)setShouldShowHudView:(BOOL)shouldShowHudView
{
810 811 812
    if (shouldShowHudView == _shouldShowHudView) {
        return;
    }
Z
Zhang Rui 已提交
813 814 815 816 817 818 819 820 821 822 823 824
    _shouldShowHudView = shouldShowHudView;
    if (shouldShowHudView)
        [self startHudTimer];
    else
        [self stopHudTimer];
}

- (BOOL)shouldShowHudView
{
    return _shouldShowHudView;
}

Z
Zhang Rui 已提交
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
- (void)setPlaybackRate:(float)playbackRate
{
    if (!_mediaPlayer)
        return;

    return ijkmp_set_playback_rate(_mediaPlayer, playbackRate);
}

- (float)playbackRate
{
    if (!_mediaPlayer)
        return 0.0f;

    return ijkmp_get_property_float(_mediaPlayer, FFP_PROP_FLOAT_PLAYBACK_RATE, 0.0f);
}

Z
Zhang Rui 已提交
841 842 843 844 845 846
inline static void fillMetaInternal(NSMutableDictionary *meta, IjkMediaMeta *rawMeta, const char *name, NSString *defaultValue)
{
    if (!meta || !rawMeta || !name)
        return;

    NSString *key = [NSString stringWithUTF8String:name];
Z
Zhang Rui 已提交
847
    const char *value = ijkmeta_get_string_l(rawMeta, name);
Z
Zhang Rui 已提交
848 849
    if (value) {
        [meta setObject:[NSString stringWithUTF8String:value] forKey:key];
Z
zccicy 已提交
850
    } else if (defaultValue) {
Z
Zhang Rui 已提交
851 852 853 854 855 856
        [meta setObject:defaultValue forKey:key];
    } else {
        [meta removeObjectForKey:key];
    }
}

Z
Zhang Rui 已提交
857
- (void)postEvent: (IJKFFMoviePlayerMessage *)msg
858 859 860 861 862 863 864 865
{
    if (!msg)
        return;

    AVMessage *avmsg = &msg->_msg;
    switch (avmsg->what) {
        case FFP_MSG_FLUSH:
            break;
866
        case FFP_MSG_ERROR: {
867
            NSLog(@"FFP_MSG_ERROR: %d\n", avmsg->arg1);
868

869
            [self setScreenOn:NO];
870

871
            [[NSNotificationCenter defaultCenter]
872
             postNotificationName:IJKMPMoviePlayerPlaybackStateDidChangeNotification
Z
Zhang Rui 已提交
873
             object:self];
874 875

            [[NSNotificationCenter defaultCenter]
876
                postNotificationName:IJKMPMoviePlayerPlaybackDidFinishNotification
877 878
                object:self
                userInfo:@{
879
                    IJKMPMoviePlayerPlaybackDidFinishReasonUserInfoKey: @(IJKMPMovieFinishReasonPlaybackError),
880
                    @"error": @(avmsg->arg1)}];
881
            break;
882
        }
Z
Zhang Rui 已提交
883
        case FFP_MSG_PREPARED: {
884
            NSLog(@"FFP_MSG_PREPARED:\n");
885

Z
Zhang Rui 已提交
886 887
            _monitor.prepareDuration = (int64_t)SDL_GetTickHR() - _monitor.prepareStartTick;

Z
Zhang Rui 已提交
888 889 890 891 892 893 894 895 896 897 898
            IjkMediaMeta *rawMeta = ijkmp_get_meta_l(_mediaPlayer);
            if (rawMeta) {
                ijkmeta_lock(rawMeta);

                NSMutableDictionary *newMediaMeta = [[NSMutableDictionary alloc] init];

                fillMetaInternal(newMediaMeta, rawMeta, IJKM_KEY_FORMAT, nil);
                fillMetaInternal(newMediaMeta, rawMeta, IJKM_KEY_DURATION_US, nil);
                fillMetaInternal(newMediaMeta, rawMeta, IJKM_KEY_START_US, nil);
                fillMetaInternal(newMediaMeta, rawMeta, IJKM_KEY_BITRATE, nil);

Z
Zhang Rui 已提交
899 900
                fillMetaInternal(newMediaMeta, rawMeta, IJKM_KEY_VIDEO_STREAM, nil);
                fillMetaInternal(newMediaMeta, rawMeta, IJKM_KEY_AUDIO_STREAM, nil);
Z
Zhang Rui 已提交
901 902 903 904 905 906 907 908 909 910 911 912 913

                int64_t video_stream = ijkmeta_get_int64_l(rawMeta, IJKM_KEY_VIDEO_STREAM, -1);
                int64_t audio_stream = ijkmeta_get_int64_l(rawMeta, IJKM_KEY_AUDIO_STREAM, -1);

                NSMutableArray *streams = [[NSMutableArray alloc] init];

                size_t count = ijkmeta_get_children_count_l(rawMeta);
                for(size_t i = 0; i < count; ++i) {
                    IjkMediaMeta *streamRawMeta = ijkmeta_get_child_l(rawMeta, i);
                    NSMutableDictionary *streamMeta = [[NSMutableDictionary alloc] init];

                    if (streamRawMeta) {
                        fillMetaInternal(streamMeta, streamRawMeta, IJKM_KEY_TYPE, k_IJKM_VAL_TYPE__UNKNOWN);
Z
Zhang Rui 已提交
914
                        const char *type = ijkmeta_get_string_l(streamRawMeta, IJKM_KEY_TYPE);
Z
Zhang Rui 已提交
915
                        if (type) {
Z
Zhang Rui 已提交
916 917 918 919
                            fillMetaInternal(streamMeta, streamRawMeta, IJKM_KEY_CODEC_NAME, nil);
                            fillMetaInternal(streamMeta, streamRawMeta, IJKM_KEY_CODEC_PROFILE, nil);
                            fillMetaInternal(streamMeta, streamRawMeta, IJKM_KEY_CODEC_LONG_NAME, nil);
                            fillMetaInternal(streamMeta, streamRawMeta, IJKM_KEY_BITRATE, nil);
Z
Zhang Rui 已提交
920 921

                            if (0 == strcmp(type, IJKM_VAL_TYPE__VIDEO)) {
Z
Zhang Rui 已提交
922 923 924 925 926 927 928 929 930 931
                                fillMetaInternal(streamMeta, streamRawMeta, IJKM_KEY_WIDTH, nil);
                                fillMetaInternal(streamMeta, streamRawMeta, IJKM_KEY_HEIGHT, nil);
                                fillMetaInternal(streamMeta, streamRawMeta, IJKM_KEY_FPS_NUM, nil);
                                fillMetaInternal(streamMeta, streamRawMeta, IJKM_KEY_FPS_DEN, nil);
                                fillMetaInternal(streamMeta, streamRawMeta, IJKM_KEY_TBR_NUM, nil);
                                fillMetaInternal(streamMeta, streamRawMeta, IJKM_KEY_TBR_DEN, nil);
                                fillMetaInternal(streamMeta, streamRawMeta, IJKM_KEY_SAR_NUM, nil);
                                fillMetaInternal(streamMeta, streamRawMeta, IJKM_KEY_SAR_DEN, nil);

                                if (video_stream == i) {
Z
Zhang Rui 已提交
932
                                    _monitor.videoMeta = streamMeta;
Z
Zhang Rui 已提交
933

Z
Zhang Rui 已提交
934 935
                                    int64_t fps_num = ijkmeta_get_int64_l(streamRawMeta, IJKM_KEY_FPS_NUM, 0);
                                    int64_t fps_den = ijkmeta_get_int64_l(streamRawMeta, IJKM_KEY_FPS_DEN, 0);
Z
Zhang Rui 已提交
936 937 938 939 940 941 942
                                    if (fps_num > 0 && fps_den > 0) {
                                        _fpsInMeta = ((CGFloat)(fps_num)) / fps_den;
                                        NSLog(@"fps in meta %f\n", _fpsInMeta);
                                    }
                                }

                            } else if (0 == strcmp(type, IJKM_VAL_TYPE__AUDIO)) {
Z
Zhang Rui 已提交
943 944
                                fillMetaInternal(streamMeta, streamRawMeta, IJKM_KEY_SAMPLE_RATE, nil);
                                fillMetaInternal(streamMeta, streamRawMeta, IJKM_KEY_CHANNEL_LAYOUT, nil);
Z
Zhang Rui 已提交
945

Z
Zhang Rui 已提交
946
                                if (audio_stream == i) {
Z
Zhang Rui 已提交
947
                                    _monitor.audioMeta = streamMeta;
Z
Zhang Rui 已提交
948 949 950 951 952 953 954 955 956 957 958
                                }
                            }
                        }
                    }

                    [streams addObject:streamMeta];
                }

                [newMediaMeta setObject:streams forKey:kk_IJKM_KEY_STREAMS];

                ijkmeta_unlock(rawMeta);
Z
Zhang Rui 已提交
959
                _monitor.mediaMeta = newMediaMeta;
Z
Zhang Rui 已提交
960 961
            }

Z
Zhang Rui 已提交
962
            [self startHudTimer];
B
bbcallen 已提交
963
            _isPreparedToPlay = YES;
964

965
            [[NSNotificationCenter defaultCenter] postNotificationName:IJKMPMediaPlaybackIsPreparedToPlayDidChangeNotification object:self];
966

967
            _loadState = IJKMPMovieLoadStatePlayable | IJKMPMovieLoadStatePlaythroughOK;
B
bbcallen 已提交
968 969

            [[NSNotificationCenter defaultCenter]
970
             postNotificationName:IJKMPMoviePlayerLoadStateDidChangeNotification
B
bbcallen 已提交
971 972
             object:self];

973
            break;
Z
Zhang Rui 已提交
974
        }
975 976
        case FFP_MSG_COMPLETED: {

977
            [self setScreenOn:NO];
978

979
            [[NSNotificationCenter defaultCenter]
980
             postNotificationName:IJKMPMoviePlayerPlaybackStateDidChangeNotification
Z
Zhang Rui 已提交
981
             object:self];
982 983

            [[NSNotificationCenter defaultCenter]
984
             postNotificationName:IJKMPMoviePlayerPlaybackDidFinishNotification
985
             object:self
986
             userInfo:@{IJKMPMoviePlayerPlaybackDidFinishReasonUserInfoKey: @(IJKMPMovieFinishReasonPlaybackEnded)}];
987
            break;
988
        }
989
        case FFP_MSG_VIDEO_SIZE_CHANGED:
990
            NSLog(@"FFP_MSG_VIDEO_SIZE_CHANGED: %d, %d\n", avmsg->arg1, avmsg->arg2);
991 992 993 994
            if (avmsg->arg1 > 0)
                _videoWidth = avmsg->arg1;
            if (avmsg->arg2 > 0)
                _videoHeight = avmsg->arg2;
995
            [self changeNaturalSize];
996 997
            break;
        case FFP_MSG_SAR_CHANGED:
998
            NSLog(@"FFP_MSG_SAR_CHANGED: %d, %d\n", avmsg->arg1, avmsg->arg2);
999 1000 1001 1002
            if (avmsg->arg1 > 0)
                _sampleAspectRatioNumerator = avmsg->arg1;
            if (avmsg->arg2 > 0)
                _sampleAspectRatioDenominator = avmsg->arg2;
1003
            [self changeNaturalSize];
1004
            break;
1005
        case FFP_MSG_BUFFERING_START: {
1006
            NSLog(@"FFP_MSG_BUFFERING_START:\n");
1007

Z
Zhang Rui 已提交
1008 1009
            _monitor.lastPrerollStartTick = (int64_t)SDL_GetTickHR();

1010
            _loadState = IJKMPMovieLoadStateStalled;
1011 1012

            [[NSNotificationCenter defaultCenter]
1013
             postNotificationName:IJKMPMoviePlayerLoadStateDidChangeNotification
1014
             object:self];
1015
            break;
1016 1017
        }
        case FFP_MSG_BUFFERING_END: {
1018
            NSLog(@"FFP_MSG_BUFFERING_END:\n");
1019

Z
Zhang Rui 已提交
1020 1021
            _monitor.lastPrerollDuration = (int64_t)SDL_GetTickHR() - _monitor.lastPrerollStartTick;

1022
            _loadState = IJKMPMovieLoadStatePlayable | IJKMPMovieLoadStatePlaythroughOK;
1023 1024

            [[NSNotificationCenter defaultCenter]
1025
             postNotificationName:IJKMPMoviePlayerLoadStateDidChangeNotification
1026
             object:self];
B
bbcallen 已提交
1027
            [[NSNotificationCenter defaultCenter]
1028
             postNotificationName:IJKMPMoviePlayerPlaybackStateDidChangeNotification
B
bbcallen 已提交
1029
             object:self];
1030
            break;
1031
        }
1032
        case FFP_MSG_BUFFERING_UPDATE:
Z
Zhang Rui 已提交
1033 1034
            _bufferingPosition = avmsg->arg1;
            _bufferingProgress = avmsg->arg2;
1035
            // NSLog(@"FFP_MSG_BUFFERING_UPDATE: %d, %%%d\n", _bufferingPosition, _bufferingProgress);
1036 1037
            break;
        case FFP_MSG_BUFFERING_BYTES_UPDATE:
1038
            // NSLog(@"FFP_MSG_BUFFERING_BYTES_UPDATE: %d\n", avmsg->arg1);
1039 1040
            break;
        case FFP_MSG_BUFFERING_TIME_UPDATE:
Z
Zhang Rui 已提交
1041
            _bufferingTime       = avmsg->arg1;
1042
            // NSLog(@"FFP_MSG_BUFFERING_TIME_UPDATE: %d\n", avmsg->arg1);
1043
            break;
B
bbcallen 已提交
1044 1045
        case FFP_MSG_PLAYBACK_STATE_CHANGED:
            [[NSNotificationCenter defaultCenter]
1046
             postNotificationName:IJKMPMoviePlayerPlaybackStateDidChangeNotification
B
bbcallen 已提交
1047 1048
             object:self];
            break;
B
bbcallen 已提交
1049
        case FFP_MSG_SEEK_COMPLETE: {
1050
            NSLog(@"FFP_MSG_SEEK_COMPLETE:\n");
Z
Zhang Rui 已提交
1051 1052 1053 1054 1055
            [[NSNotificationCenter defaultCenter]
             postNotificationName:IJKMPMoviePlayerDidSeekCompleteNotification
             object:self
             userInfo:@{IJKMPMoviePlayerDidSeekCompleteTargetKey: @(avmsg->arg1),
                        IJKMPMoviePlayerDidSeekCompleteErrorKey: @(avmsg->arg2)}];
B
bbcallen 已提交
1056
            _seeking = NO;
1057
            break;
B
bbcallen 已提交
1058
        }
Z
Zhang Rui 已提交
1059 1060
        case FFP_MSG_VIDEO_DECODER_OPEN: {
            _isVideoToolboxOpen = avmsg->arg1;
1061
            NSLog(@"FFP_MSG_VIDEO_DECODER_OPEN: %@\n", _isVideoToolboxOpen ? @"true" : @"false");
Z
Zhang Rui 已提交
1062
            [[NSNotificationCenter defaultCenter]
1063
             postNotificationName:IJKMPMoviePlayerVideoDecoderOpenNotification
Z
Zhang Rui 已提交
1064 1065 1066
             object:self];
            break;
        }
1067 1068
        case FFP_MSG_VIDEO_RENDERING_START: {
            NSLog(@"FFP_MSG_VIDEO_RENDERING_START:\n");
Z
Zhang Rui 已提交
1069
            _monitor.firstVideoFrameLatency = (int64_t)SDL_GetTickHR() - _monitor.prepareStartTick;
1070
            [[NSNotificationCenter defaultCenter]
1071
             postNotificationName:IJKMPMoviePlayerFirstVideoFrameRenderedNotification
1072 1073 1074 1075 1076 1077
             object:self];
            break;
        }
        case FFP_MSG_AUDIO_RENDERING_START: {
            NSLog(@"FFP_MSG_AUDIO_RENDERING_START:\n");
            [[NSNotificationCenter defaultCenter]
1078
             postNotificationName:IJKMPMoviePlayerFirstAudioFrameRenderedNotification
1079 1080 1081
             object:self];
            break;
        }
1082
        default:
1083
            // NSLog(@"unknown FFP_MSG_xxx(%d)\n", avmsg->what);
1084 1085
            break;
    }
Z
Zhang Rui 已提交
1086 1087 1088 1089

    [_msgPool recycle:msg];
}

Z
Zhang Rui 已提交
1090
- (IJKFFMoviePlayerMessage *) obtainMessage {
Z
Zhang Rui 已提交
1091
    return [_msgPool obtain];
1092 1093
}

Z
Zhang Rui 已提交
1094 1095
inline static IJKFFMoviePlayerController *ffplayerRetain(void *arg) {
    return (__bridge_transfer IJKFFMoviePlayerController *) arg;
Z
Zhang Rui 已提交
1096 1097
}

1098
int media_player_msg_loop(void* arg)
1099
{
1100 1101
    @autoreleasepool {
        IjkMediaPlayer *mp = (IjkMediaPlayer*)arg;
Z
Zhang Rui 已提交
1102
        __weak IJKFFMoviePlayerController *ffpController = ffplayerRetain(ijkmp_set_weak_thiz(mp, NULL));
1103
        while (ffpController) {
1104
            @autoreleasepool {
Z
Zhang Rui 已提交
1105
                IJKFFMoviePlayerMessage *msg = [ffpController obtainMessage];
Z
Zhang Rui 已提交
1106 1107 1108
                if (!msg)
                    break;

1109 1110 1111
                int retval = ijkmp_get_msg(mp, &msg->_msg, 1);
                if (retval < 0)
                    break;
1112

1113 1114 1115
                // block-get should never return 0
                assert(retval > 0);
                [ffpController performSelectorOnMainThread:@selector(postEvent:) withObject:msg waitUntilDone:NO];
1116 1117
            }
        }
1118

Z
Zhang Rui 已提交
1119 1120
        // retained in prepare_async, before SDL_CreateThreadEx
        ijkmp_dec_ref_p(&mp);
1121 1122
        return 0;
    }
1123 1124
}

1125 1126
#pragma mark av_format_control_message

1127
static int onInjectIOControl(IJKFFMoviePlayerController *mpc, id<IJKMediaUrlOpenDelegate> delegate, int type, void *data, size_t data_size)
1128
{
1129
    AVAppIOControl *realData = data;
Z
Zhang Rui 已提交
1130
    assert(realData);
1131
    assert(sizeof(AVAppIOControl) == data_size);
Z
Zhang Rui 已提交
1132 1133
    realData->is_handled     = NO;
    realData->is_url_changed = NO;
1134

Z
Zhang Rui 已提交
1135
    if (delegate == nil)
1136
        return 0;
Z
Zhang Rui 已提交
1137

Z
Zhang Rui 已提交
1138 1139
    NSString *urlString = [NSString stringWithUTF8String:realData->url];

Z
Zhang Rui 已提交
1140
    IJKMediaUrlOpenData *openData =
Z
Zhang Rui 已提交
1141
    [[IJKMediaUrlOpenData alloc] initWithUrl:urlString
Z
Zhang Rui 已提交
1142
                                       event:(IJKMediaEvent)type
Z
Zhang Rui 已提交
1143 1144
                                segmentIndex:realData->segment_index
                                retryCounter:realData->retry_counter];
Z
Zhang Rui 已提交
1145

Z
Zhang Rui 已提交
1146 1147
    [delegate willOpenUrl:openData];
    if (openData.error < 0)
1148 1149
        return -1;

Z
Zhang Rui 已提交
1150 1151 1152 1153 1154 1155 1156 1157
    if (openData.isHandled) {
        realData->is_handled = YES;
        if (openData.isUrlChanged && openData.url != nil) {
            realData->is_url_changed = YES;
            const char *newUrlUTF8 = [openData.url UTF8String];
            strlcpy(realData->url, newUrlUTF8, sizeof(realData->url));
            realData->url[sizeof(realData->url) - 1] = 0;
        }
Z
Zhang Rui 已提交
1158
    }
Z
Zhang Rui 已提交
1159
    
Z
Zhang Rui 已提交
1160 1161 1162
    return 0;
}

1163
static int onInjectTcpIOControl(IJKFFMoviePlayerController *mpc, id<IJKMediaUrlOpenDelegate> delegate, int type, void *data, size_t data_size)
Z
Zhang Rui 已提交
1164
{
1165
    AVAppTcpIOControl *realData = data;
Z
Zhang Rui 已提交
1166
    assert(realData);
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
    assert(sizeof(AVAppTcpIOControl) == data_size);

    switch (type) {
        case IJKMediaCtrl_WillTcpOpen:

            break;
        case IJKMediaCtrl_DidTcpOpen:
            mpc->_monitor.tcpError = realData->error;
            mpc->_monitor.remoteIp = [NSString stringWithUTF8String:realData->ip];
            [mpc->_glView setHudValue: mpc->_monitor.remoteIp forKey:@"ip"];
            break;
        default:
            assert(!"unexcepted type for tcp io control");
            break;
    }

    if (delegate == nil)
        return 0;

    NSString *urlString = [NSString stringWithUTF8String:realData->ip];

    IJKMediaUrlOpenData *openData =
    [[IJKMediaUrlOpenData alloc] initWithUrl:urlString
                                       event:(IJKMediaEvent)type
                                segmentIndex:0
                                retryCounter:0];
    openData.fd = realData->fd;

    [delegate willOpenUrl:openData];
    if (openData.error < 0)
        return -1;
1198
    [mpc->_glView setHudValue: [NSString stringWithFormat:@"fd:%d %@", openData.fd, openData.msg?:@"unknown"] forKey:@"tcp-info"];
Z
Zhang Rui 已提交
1199 1200 1201
    return 0;
}

1202
static int onInjectAsyncStatistic(IJKFFMoviePlayerController *mpc, int type, void *data, size_t data_size)
Z
Zhang Rui 已提交
1203
{
1204
    AVAppAsyncStatistic *realData = data;
Z
Zhang Rui 已提交
1205
    assert(realData);
1206
    assert(sizeof(AVAppAsyncStatistic) == data_size);
Z
Zhang Rui 已提交
1207

1208
    mpc->_asyncStat = *realData;
Z
Zhang Rui 已提交
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
    return 0;
}

static int64_t calculateElapsed(int64_t begin, int64_t end)
{
    if (begin <= 0)
        return -1;

    if (end < begin)
        return -1;

    return end - begin;
}

static int onInjectOnHttpEvent(IJKFFMoviePlayerController *mpc, int type, void *data, size_t data_size)
Z
Zhang Rui 已提交
1224
{
Z
Zhang Rui 已提交
1225
    AVAppHttpEvent *realData = data;
Z
Zhang Rui 已提交
1226
    assert(realData);
Z
Zhang Rui 已提交
1227 1228 1229 1230 1231 1232 1233
    assert(sizeof(AVAppHttpEvent) == data_size);

    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    NSURL        *nsurl   = nil;
    IJKFFMonitor *monitor = mpc->_monitor;
    NSString     *url  = monitor.httpUrl;
    NSString     *host = monitor.httpHost;
1234
    int64_t       elapsed = 0;
Z
Zhang Rui 已提交
1235 1236 1237 1238

    id<IJKMediaNativeInvokeDelegate> delegate = mpc.nativeInvokeDelegate;

    switch (type) {
1239
        case AVAPP_EVENT_WILL_HTTP_OPEN:
Z
Zhang Rui 已提交
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
            url   = [NSString stringWithUTF8String:realData->url];
            nsurl = [NSURL URLWithString:url];
            host  = nsurl.host;

            monitor.httpUrl      = url;
            monitor.httpHost     = host;
            monitor.httpOpenTick = SDL_GetTickHR();
            [mpc setHudUrl:url];

            if (delegate != nil) {
                dict[IJKMediaEventAttrKey_host]         = [NSString ijk_stringBeEmptyIfNil:host];
                [delegate invoke:type attributes:dict];
            }
            break;
1254
        case AVAPP_EVENT_DID_HTTP_OPEN:
1255
            elapsed = calculateElapsed(monitor.httpOpenTick, SDL_GetTickHR());
Z
Zhang Rui 已提交
1256 1257
            monitor.httpError = realData->error;
            monitor.httpCode  = realData->http_code;
Z
Zhang Rui 已提交
1258
            monitor.httpOpenCount++;
1259 1260
            monitor.httpOpenTick = 0;
            monitor.lastHttpOpenDuration = elapsed;
Z
Zhang Rui 已提交
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
            [mpc->_glView setHudValue:@(realData->http_code).stringValue forKey:@"http"];

            if (delegate != nil) {
                dict[IJKMediaEventAttrKey_time_of_event]    = @(elapsed).stringValue;
                dict[IJKMediaEventAttrKey_url]              = [NSString ijk_stringBeEmptyIfNil:monitor.httpUrl];
                dict[IJKMediaEventAttrKey_host]             = [NSString ijk_stringBeEmptyIfNil:host];
                dict[IJKMediaEventAttrKey_error]            = @(realData->error).stringValue;
                dict[IJKMediaEventAttrKey_http_code]        = @(realData->http_code).stringValue;
                [delegate invoke:type attributes:dict];
            }
            break;
1272
        case AVAPP_EVENT_WILL_HTTP_SEEK:
Z
Zhang Rui 已提交
1273
            monitor.httpSeekTick = SDL_GetTickHR();
Z
Zhang Rui 已提交
1274

Z
Zhang Rui 已提交
1275 1276 1277 1278 1279 1280
            if (delegate != nil) {
                dict[IJKMediaEventAttrKey_host]         = [NSString ijk_stringBeEmptyIfNil:host];
                dict[IJKMediaEventAttrKey_offset]       = @(realData->offset).stringValue;
                [delegate invoke:type attributes:dict];
            }
            break;
1281
        case AVAPP_EVENT_DID_HTTP_SEEK:
1282
            elapsed = calculateElapsed(monitor.httpSeekTick, SDL_GetTickHR());
Z
Zhang Rui 已提交
1283 1284
            monitor.httpError = realData->error;
            monitor.httpCode  = realData->http_code;
Z
Zhang Rui 已提交
1285
            monitor.httpSeekCount++;
1286 1287
            monitor.httpSeekTick = 0;
            monitor.lastHttpSeekDuration = elapsed;
Z
Zhang Rui 已提交
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
            [mpc->_glView setHudValue:@(realData->http_code).stringValue forKey:@"http"];

            if (delegate != nil) {
                dict[IJKMediaEventAttrKey_time_of_event]    = @(elapsed).stringValue;
                dict[IJKMediaEventAttrKey_url]              = [NSString ijk_stringBeEmptyIfNil:monitor.httpUrl];
                dict[IJKMediaEventAttrKey_host]             = [NSString ijk_stringBeEmptyIfNil:host];
                dict[IJKMediaEventAttrKey_offset]           = @(realData->offset).stringValue;
                dict[IJKMediaEventAttrKey_error]            = @(realData->error).stringValue;
                dict[IJKMediaEventAttrKey_http_code]        = @(realData->http_code).stringValue;
                [delegate invoke:type attributes:dict];
            }
            break;
Z
Zhang Rui 已提交
1300 1301 1302 1303 1304
    }

    return 0;
}

Z
Zhang Rui 已提交
1305 1306
// NOTE: could be called from multiple thread
static int ijkff_inject_callback(void *opaque, int message, void *data, size_t data_size)
1307
{
1308 1309 1310 1311
    IJKWeakHolder *weakHolder = (__bridge IJKWeakHolder*)opaque;
    IJKFFMoviePlayerController *mpc = weakHolder.object;
    if (!mpc)
        return 0;
1312

Z
Zhang Rui 已提交
1313
    switch (message) {
1314 1315 1316 1317 1318 1319 1320 1321 1322
        case AVAPP_CTRL_WILL_CONCAT_SEGMENT_OPEN:
            return onInjectIOControl(mpc, mpc.segmentOpenDelegate, message, data, data_size);
        case AVAPP_CTRL_WILL_TCP_OPEN:
            return onInjectTcpIOControl(mpc, mpc.tcpOpenDelegate, message, data, data_size);
        case AVAPP_CTRL_WILL_HTTP_OPEN:
            return onInjectIOControl(mpc, mpc.httpOpenDelegate, message, data, data_size);
        case AVAPP_CTRL_WILL_LIVE_OPEN:
            return onInjectIOControl(mpc, mpc.liveOpenDelegate, message, data, data_size);
        case AVAPP_EVENT_ASYNC_STATISTIC:
Z
Zhang Rui 已提交
1323
            return onInjectAsyncStatistic(mpc, message, data, data_size);
1324 1325 1326 1327 1328 1329
        case AVAPP_CTRL_DID_TCP_OPEN:
            return onInjectTcpIOControl(mpc, mpc.tcpOpenDelegate, message, data, data_size);
        case AVAPP_EVENT_WILL_HTTP_OPEN:
        case AVAPP_EVENT_DID_HTTP_OPEN:
        case AVAPP_EVENT_WILL_HTTP_SEEK:
        case AVAPP_EVENT_DID_HTTP_SEEK:
Z
Zhang Rui 已提交
1330
            return onInjectOnHttpEvent(mpc, message, data, data_size);
1331
        default: {
Z
Zhang Rui 已提交
1332
            return 0;
1333 1334 1335 1336
        }
    }
}

Y
airplay  
yuvesy@yuvesy.com 已提交
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
#pragma mark Airplay

-(BOOL)allowsMediaAirPlay
{
    if (!self)
        return NO;
    return _allowsMediaAirPlay;
}

-(void)setAllowsMediaAirPlay:(BOOL)b
{
    if (!self)
        return;
    _allowsMediaAirPlay = b;
}

-(BOOL)airPlayMediaActive
{
    if (!self)
        return NO;
Y
yuvesy@yuvesy.com 已提交
1357 1358 1359 1360
    if (_isDanmakuMediaAirPlay) {
        return YES;
    }
    return NO;
Y
airplay  
yuvesy@yuvesy.com 已提交
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
}

-(BOOL)isDanmakuMediaAirPlay
{
    return _isDanmakuMediaAirPlay;
}

-(void)setIsDanmakuMediaAirPlay:(BOOL)isDanmakuMediaAirPlay
{
    _isDanmakuMediaAirPlay = isDanmakuMediaAirPlay;
Y
yuvesy@yuvesy.com 已提交
1371
    if (_isDanmakuMediaAirPlay) {
Y
yuvesy@yuvesy.com 已提交
1372
        _glView.scaleFactor = 1.0f;
Y
yuvesy@yuvesy.com 已提交
1373 1374 1375
    }
    else {
        CGFloat scale = [[UIScreen mainScreen] scale];
Y
yuvesy@yuvesy.com 已提交
1376
        if (scale < 0.1f)
Y
yuvesy@yuvesy.com 已提交
1377 1378 1379
            scale = 1.0f;
        _glView.scaleFactor = scale;
    }
1380
     [[NSNotificationCenter defaultCenter] postNotificationName:IJKMPMoviePlayerIsAirPlayVideoActiveDidChangeNotification object:nil userInfo:nil];
Y
airplay  
yuvesy@yuvesy.com 已提交
1381 1382
}

1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430

#pragma mark Option Conventionce

- (void)setFormatOptionValue:(NSString *)value forKey:(NSString *)key
{
    [self setOptionValue:value forKey:key ofCategory:kIJKFFOptionCategoryFormat];
}

- (void)setCodecOptionValue:(NSString *)value forKey:(NSString *)key
{
    [self setOptionValue:value forKey:key ofCategory:kIJKFFOptionCategoryCodec];
}

- (void)setSwsOptionValue:(NSString *)value forKey:(NSString *)key
{
    [self setOptionValue:value forKey:key ofCategory:kIJKFFOptionCategorySws];
}

- (void)setPlayerOptionValue:(NSString *)value forKey:(NSString *)key
{
    [self setOptionValue:value forKey:key ofCategory:kIJKFFOptionCategoryPlayer];
}

- (void)setFormatOptionIntValue:(int64_t)value forKey:(NSString *)key
{
    [self setOptionIntValue:value forKey:key ofCategory:kIJKFFOptionCategoryFormat];
}

- (void)setCodecOptionIntValue:(int64_t)value forKey:(NSString *)key
{
    [self setOptionIntValue:value forKey:key ofCategory:kIJKFFOptionCategoryCodec];
}

- (void)setSwsOptionIntValue:(int64_t)value forKey:(NSString *)key
{
    [self setOptionIntValue:value forKey:key ofCategory:kIJKFFOptionCategorySws];
}

- (void)setPlayerOptionIntValue:(int64_t)value forKey:(NSString *)key
{
    [self setOptionIntValue:value forKey:key ofCategory:kIJKFFOptionCategoryPlayer];
}

- (void)setMaxBufferSize:(int)maxBufferSize
{
    [self setPlayerOptionIntValue:maxBufferSize forKey:@"max-buffer-size"];
}

1431 1432 1433 1434
#pragma mark app state changed

- (void)registerApplicationObservers
{
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
    [_notificationManager addObserver:self
                             selector:@selector(audioSessionInterrupt:)
                                 name:AVAudioSessionInterruptionNotification
                               object:nil];

    [_notificationManager addObserver:self
                             selector:@selector(applicationWillEnterForeground)
                                 name:UIApplicationWillEnterForegroundNotification
                               object:nil];

    [_notificationManager addObserver:self
                             selector:@selector(applicationDidBecomeActive)
                                 name:UIApplicationDidBecomeActiveNotification
                               object:nil];

    [_notificationManager addObserver:self
                             selector:@selector(applicationWillResignActive)
                                 name:UIApplicationWillResignActiveNotification
                               object:nil];

    [_notificationManager addObserver:self
                             selector:@selector(applicationDidEnterBackground)
                                 name:UIApplicationDidEnterBackgroundNotification
                               object:nil];

    [_notificationManager addObserver:self
                             selector:@selector(applicationWillTerminate)
                                 name:UIApplicationWillTerminateNotification
                               object:nil];
1464 1465 1466 1467
}

- (void)unregisterApplicationObservers
{
1468
    [_notificationManager removeAllObservers:self];
1469 1470
}

1471 1472 1473 1474 1475 1476
- (void)audioSessionInterrupt:(NSNotification *)notification
{
    int reason = [[[notification userInfo] valueForKey:AVAudioSessionInterruptionTypeKey] intValue];
    switch (reason) {
        case AVAudioSessionInterruptionTypeBegan: {
            NSLog(@"IJKFFMoviePlayerController:audioSessionInterrupt: begin\n");
1477
            switch (self.playbackState) {
1478 1479
                case IJKMPMoviePlaybackStatePaused:
                case IJKMPMoviePlaybackStateStopped:
1480 1481 1482 1483 1484 1485
                    _playingBeforeInterruption = NO;
                    break;
                default:
                    _playingBeforeInterruption = YES;
                    break;
            }
1486 1487 1488 1489 1490 1491 1492
            [self pause];
            [[IJKAudioKit sharedInstance] setActive:NO];
            break;
        }
        case AVAudioSessionInterruptionTypeEnded: {
            NSLog(@"IJKFFMoviePlayerController:audioSessionInterrupt: end\n");
            [[IJKAudioKit sharedInstance] setActive:YES];
1493 1494 1495
            if (_playingBeforeInterruption) {
                [self play];
            }
1496 1497 1498 1499 1500
            break;
        }
    }
}

1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
- (void)applicationWillEnterForeground
{
    NSLog(@"IJKFFMoviePlayerController:applicationWillEnterForeground: %d", (int)[UIApplication sharedApplication].applicationState);
}

- (void)applicationDidBecomeActive
{
    NSLog(@"IJKFFMoviePlayerController:applicationDidBecomeActive: %d", (int)[UIApplication sharedApplication].applicationState);
}

- (void)applicationWillResignActive
{
    NSLog(@"IJKFFMoviePlayerController:applicationWillResignActive: %d", (int)[UIApplication sharedApplication].applicationState);
    dispatch_async(dispatch_get_main_queue(), ^{
Z
Zhang Rui 已提交
1515 1516 1517
        if (_pauseInBackground) {
            [self pause];
        }
1518 1519 1520 1521 1522 1523 1524
    });
}

- (void)applicationDidEnterBackground
{
    NSLog(@"IJKFFMoviePlayerController:applicationDidEnterBackground: %d", (int)[UIApplication sharedApplication].applicationState);
    dispatch_async(dispatch_get_main_queue(), ^{
Z
Zhang Rui 已提交
1525 1526 1527
        if (_pauseInBackground) {
            [self pause];
        }
1528 1529 1530 1531 1532 1533 1534
    });
}

- (void)applicationWillTerminate
{
    NSLog(@"IJKFFMoviePlayerController:applicationWillTerminate: %d", (int)[UIApplication sharedApplication].applicationState);
    dispatch_async(dispatch_get_main_queue(), ^{
Z
Zhang Rui 已提交
1535 1536 1537
        if (_pauseInBackground) {
            [self pause];
        }
1538 1539 1540
    });
}

1541
@end
1542