StreamerDetailViewController.m 18.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 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 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
//
//  LiveViewController.m
//  CNLiveLiveDemo
//
//  Created by Android on 16/8/10.
//  Copyright © 2016年 Android. All rights reserved.
//

#import "StreamerDetailViewController.h"
#import <CNLivePlayerSDK/CNLiveGPUStreamerKit.h>
#import <CNLivePlayerSDK/CNLiveWebcastManager.h>
#import "FilterFunctionView.h"

#define Width [UIScreen mainScreen].bounds.size.width
#define Height [UIScreen mainScreen].bounds.size.height

#define KAppId @"60_irn9edco29"
#define KAppKey @"69fe70bda67e059286ad509d9f5377f815955645b52f94"
#define KBundleId @"com.cnlive.video"

@interface StreamerDetailViewController ()<UIGestureRecognizerDelegate>
{
    UIButton *_startLiveBtn;
    CGFloat _currentPinchZoomFactor;//当前触摸缩放因子
}

@property (nonatomic,strong) UIView *captureView;
@property (nonatomic,strong) UILabel *stateLab;
@property (nonatomic,strong) NSURL *hostURL;
@property (nonatomic,strong) FilterFunctionView *filterView;
@property (nonatomic,strong) CNLiveGPUStreamerKit *kitCN;        //直播推流

@end

@implementation StreamerDetailViewController

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if (_kitCN) {
        return UIInterfaceOrientationMaskAllButUpsideDown;
    } else {
        return UIInterfaceOrientationMaskPortrait;
    }
}

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    
    UIInterfaceOrientation orie = [[UIApplication sharedApplication] statusBarOrientation];
    [_kitCN rotatePreviewTo:orie];
    
    if (_kitCN.streamerBase.isStreaming) {
        [_kitCN rotateStreamTo:orie];
    }
    
    [UIView animateWithDuration:0.2 animations:^{
        _captureView.frame = self.view.bounds;
        _stateLab.frame = CGRectMake(0, Height-100, Width, 100);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.captureView];
    [self.view addSubview:self.filterView];
    [self.view addSubview:self.stateLab];
    
    if (_isAuthLive) {
        
        NSString *activityId = [NSString stringWithFormat:@"%d%d%d%d%d",arc4random()%9,arc4random()%9,arc4random()%9,arc4random()%9,arc4random()%9];

        [[CNLiveWebcastManager manager] initWithAppId:KAppId appKey:KAppKey];
        
        _kitCN = [[CNLiveGPUStreamerKit alloc] initWithDefaultConfigWithActivityId:activityId channelId:@"iOStest" isHorizontalScreen:@"0"];
        
        //        _kitCN.activityName = @"iOS test";
        //        _kitCN.coverImgUrl = @"djfiwooa";
        
        [self setStreamerCfg];
        [self addObservers];
        
    }else{
        
        _kitCN = [[CNLiveGPUStreamerKit alloc] initWithDefaultConfig];
        _hostURL = _url;
        
        [self setStreamerCfg];
        [self addObservers];
        
    }
    
    _startLiveBtn = [self addButton:@"开始直播" frame:CGRectMake(100, 40, 80, 40) action:@selector(startCapture:)];
    [_startLiveBtn setTitle:@"开始直播" forState:UIControlStateNormal];
    [_startLiveBtn setTitle:@"停止直播" forState:UIControlStateSelected];
    
    [self addButton:@"关闭预览" frame:CGRectMake(10, 40, 80, 40) action:@selector(startPreview:)];
    [self addButton:@"退出" frame:CGRectMake(190, 40, 80, 40) action:@selector(quit)];
    [self addButton:@"美颜" frame:CGRectMake(10, 100, 80, 40) action:@selector(openFilter:)];
    [self addButton:@"摄像头" frame:CGRectMake(100, 100, 80, 40) action:@selector(changeCamera:)];
    [self addButton:@"闪光灯" frame:CGRectMake(190, 100, 80, 40) action:@selector(openFlash)];
    
    
    UITapGestureRecognizer * singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTap:)];
    singleRecognizer.delegate = self;
    [self.captureView addGestureRecognizer:singleRecognizer];
    
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchDetected:)];
    [self.view addGestureRecognizer:pinch];
    
}

- (UIButton *)addButton:(NSString*)title
                  frame:(CGRect)frame
                 action:(SEL)action {
    UIButton * button;
    button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    [button setTitle: title forState: UIControlStateNormal];
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    [button setTitleColor:[UIColor colorWithRed:23/255.0 green:110/255.0 blue:254/255.0 alpha:1] forState:UIControlStateNormal];
    button.layer.cornerRadius = 10;
    button.layer.masksToBounds = YES;
    button.layer.borderColor = [UIColor blackColor].CGColor;
    button.layer.borderWidth = 1;
    [self.captureView addSubview:button];
    return button;
    
}

#pragma mark - initialization
- (void)setStreamerCfg
{
    //采集配置
    _kitCN.capPreset = AVCaptureSessionPreset640x480;
    _kitCN.previewDimension = CGSizeMake(360, 640);
    _kitCN.streamDimension = CGSizeMake(360, 640);
    _kitCN.videoFPS = 15;
    _kitCN.cameraPosition = AVCaptureDevicePositionFront;
    
    //推流配置
    _kitCN.streamerBase.videoCodec = CNLiveVideoCodec_AUTO;
    _kitCN.streamerBase.videoInitBitrate = 900;
    _kitCN.streamerBase.videoMaxBitrate = 900;
    _kitCN.streamerBase.videoMinBitrate = 300;
    _kitCN.streamerBase.maxKeyInterval = 2;
    _kitCN.streamerBase.audiokBPS = 48;
    
    //耳返
    if ([CNLiveAudioCapture isHeadsetPluggedIn]) {
        [_kitCN.audioCapture setBPlayCapturedAudio:YES];
    }
    
    //设置画面朝向
    [_kitCN setVideoOrientationBy:[[UIApplication sharedApplication] statusBarOrientation]];
    [_kitCN startPreview:self.captureView];

    //水印图片
    _kitCN.watermark.logoPic = [UIImage imageNamed:@"互动电视180x180"];
    _kitCN.watermark.logoRect = CGRectMake(0.8, 0.8, 50, 50);
    _kitCN.watermark.logoAlpha = 0.6;

    //水印文字
    _kitCN.watermark.textLabel = [[UILabel alloc] init];
    _kitCN.watermark.textLabel.text = [NSString stringWithFormat:@"cnlive"];
    _kitCN.watermark.textLabel.font = [UIFont systemFontOfSize:8];
    _kitCN.watermark.textRect = CGRectMake(0.78, 0.88, 0.2, 0.04);
    [_kitCN.watermark updateTextLabel];
  
}

#pragma mark - Action

- (void)startPreview:(UIButton *)button
{
    button.selected = !button.selected;
    if (button.selected) {
        _startLiveBtn.enabled = NO;
        [button setTitle:@"开启预览" forState:UIControlStateNormal];
        if (_kitCN.streamState == CNLiveStreamStateConnected) {
            [_kitCN stopStream];
            _startLiveBtn.selected = NO;
        }
        [_kitCN stopPreview];
    }else{
        [_kitCN startPreview:self.captureView];
        [button setTitle:@"关闭预览" forState:UIControlStateNormal];
        _startLiveBtn.enabled = YES;
    }
}

- (void)startCapture:(UIButton *)button
{
    button.selected = !button.selected;
    
    if (button.selected) {
        if (_isAuthLive) {
            
            [_kitCN startStream:^{
                NSLog(@"开启推流成功 ------- success");
            } failure:^(NSDictionary *errorDic) {
                [self toast:errorDic[@"errorMessage"]];
                _startLiveBtn.selected = NO;
            }];
            
        }else{
            [_kitCN startStream:_hostURL];
        }
    }else{
        _stateLab.text = nil;
        [_kitCN stopStream];
    }
}

- (void)openFilter:(UIButton *)button
{
    button.selected = !button.selected;
    
    if (button.selected) {
        
        _filterView.hidden = NO;
        
        __weak StreamerDetailViewController *weakself = self;
        
        _filterView.filterViewBlock = ^(float grindRatio , float whitenRatio, float intensity){
            
            [weakself.kitCN.beautifyFaceFilter filterAdjustingParameterWithGrindRatio:grindRatio
                                                                          whitenRatio:whitenRatio
                                                                            intensity:intensity];
        };
        
        _filterView.currentTypeBlock = ^(NSInteger currentType){
            [weakself.kitCN.beautifyFaceFilter  setBeautyType:currentType];
        };
        
        _filterView.currentIdxBlock = ^(NSInteger currentIdx){
            weakself.kitCN.beautifyFaceFilter.curEffectIdx = currentIdx;
        };
        
    } else {
        
        _filterView.hidden = YES;
        
    }
}

- (void)changeCamera:(UIButton *)button
{
    //    button.selected = !button.selected;
    //    if (button.selected) {
    //        _kitCN.cameraPosition = AVCaptureDevicePositionBack;
    //    }else{
    //        _kitCN.cameraPosition = AVCaptureDevicePositionFront;
    //    }
    [_kitCN switchCamera];
    
}

- (void)openFlash
{
    [_kitCN toggleTorch];
    //    [_kitCN setTorchMode:AVCaptureTorchModeOn];
}

- (void)quit
{
    if (_kitCN.streamState == CNLiveStreamStateConnected) {
        [_kitCN stopStream];
    }
    if (_kitCN.captureState == CNLiveCaptureStateCapturing) {
        [_kitCN stopPreview];
    }
    
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)addObservers
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(captureStateChange) name:CNLiveCaptureStateDidChangeNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(streamStateChange)
                                                 name:CNLiveStreamStateDidChangeNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(enterBg)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(becameActive)
                                                 name:UIApplicationDidBecomeActiveNotification
                                               object:nil];
}

#pragma mark - notification

- (void)enterBg
{
    [_kitCN appEnterBackground];
}

- (void)becameActive
{
    [_kitCN appBecomeActive];
}

- (void)captureStateChange
{
    
    if ( _kitCN.captureState == CNLiveCaptureStateIdle){
        //初始化时状态为空闲
        _stateLab.text = @"CNLiveCaptureStateIdle";
        
        return;
    }
    else if (_kitCN.captureState == CNLiveCaptureStateCapturing ) {
        //设备工作中
        _stateLab.text = @"CNLiveCaptureStateCapturing";
        
        return;
    }
    else if (_kitCN.captureState == CNLiveCaptureStateClosingCapture ) {
        //关闭采集设备中
        _stateLab.text = @"CNLiveCaptureStateClosingCapture";
        
        return;
    }
    else if (_kitCN.captureState == CNLiveCaptureStateDevAuthDenied ) {
        //设备授权被拒绝
        NSLog(@"---------CNLiveCaptureStateDevAuthDenied");
        _stateLab.text = @"camera/mic Authorization Denied";
        
        return;
    }
    else if (_kitCN.captureState == CNLiveCaptureStateParameterError ) {
        // 参数错误,无法打开
        NSLog(@"---------CNLiveCaptureStateParameterError");
        _stateLab.text = @"capture devices ParameterError";
        
        return;
    }
    else if (_kitCN.captureState == CNLiveCaptureStateDevBusy ) {
        //设备正忙,请稍后尝试
        NSLog(@"---------CNLiveCaptureStateDevBusy");
        _stateLab.text = @"device busy, try later";
        
    }
}

- (void)streamStateChange
{
    
    if (_kitCN.streamState == CNLiveStreamStateIdle) {
        NSLog(@"---------CNLiveStreamStateIdle");
        _stateLab.text = @"CNLiveStreamStateIdle";
    }
    
    if (_kitCN.streamState == CNLiveStreamStateConnected) {
        NSLog(@"---------CNLiveStreamStateConnected");
        _stateLab.text = [NSString stringWithFormat:@"CNLiveStreamStateConnected------%@",_hostURL];
    }
    
    if (_kitCN.streamState == CNLiveStreamStateConnecting) {
        NSLog(@"---------CNLiveStreamStateConnecting");
        _stateLab.text = @"CNLiveStreamStateConnecting";
    }
    
    //推流出错
    if (_kitCN.streamState == CNLiveStreamStateError) {
        NSLog(@"---------CNLiveStreamStateError");
        [self onStreamError];
    }
    
    //断开推流
    if ( _kitCN.streamState == CNLiveStreamStateDisconnecting) {
        NSLog(@"---------CNLiveStreamStateDisconnecting");
        _stateLab.text = @"CNLiveStreamStateDisconnecting";
        
    }
    
    //结束推流成功
    if ( _kitCN.streamState == CNLiveStopStreamSuccess) {
        NSLog(@"---------CNLiveStopStreamSuccess");
        _stateLab.text = @"CNLiveStopStreamSuccess";
        
    }
}

- (void)onStreamError {
    
    CNLiveStreamErrorCode err = _kitCN.streamErrorCode;
    
    NSLog(@"onErr: %lu [%@]", (unsigned long) err, _stateLab.text);
    
    if ( CNLiveStreamErrorCode_CNLiveAUTHFAILED == err ) {
        _stateLab.text = @"SDK auth failed, \npls check ak/sk";
    }
    else if ( CNLiveStreamErrorCode_CODEC_OPEN_FAILED == err) {
        _stateLab.text = @"Selected Codec not supported \n in this version";
    }
    else if ( CNLiveStreamErrorCode_CONNECT_FAILED == err) {
        _stateLab.text = @"Connecting error, pls check host url \nor network";
    }
    else if ( CNLiveStreamErrorCode_CONNECT_BREAK == err) {
        _stateLab.text = @"Connection break";
    }
    else if ( CNLiveStreamErrorCode_ABNORMAL == err) {
        _stateLab.text = @"CNLiveStreamErrorCode_ABNORMAL";
        [self toast:@"推流异常中断~~"];
        _startLiveBtn.selected = NO;
        
    } else if (err == CNLiveStreamErrorCode_CODEC_OPEN_FAILED) {
        NSLog(@"video codec open failed, try software codec");
        _kitCN.streamerBase.videoCodec = CNLiveVideoCodec_VT264;
        [self tryReconnect];
    }
    else {
        
    }
    
    // 断网重连
    if (err == CNLiveStreamErrorCode_CONNECT_BREAK || err == CNLiveStreamErrorCode_AV_SYNC_ERROR) {
        [self tryReconnect];
    }
    
}

- (void) tryReconnect
{
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC));
    dispatch_after(delay, dispatch_get_main_queue(), ^{
        
        NSLog(@"try again");
        
        [_kitCN stopStream];
        
        if (_isAuthLive) {
            
            [_kitCN startStream:^{
                NSLog(@"开启推流成功 ------- success");
                _startLiveBtn.selected = YES;
                
            } failure:^(NSDictionary *errorDic) {
                [self toast:errorDic[@"errorMessage"]];
                _startLiveBtn.selected = NO;
            }];
            
        }else{
            [_kitCN startStream:_hostURL];
        }
        
        
    });
}

//对焦与曝光
- (void)onTap:(UIGestureRecognizer *)sender
{
    CGPoint current = [sender locationInView:self.view];
    CGPoint point = [self convertToPointOfInterestFromViewCoordinates:current];
    [_kitCN exposureAtPoint:point];
    [_kitCN focusAtPoint:point];
}

//缩放
- (void)pinchDetected:(UIPinchGestureRecognizer *)recognizer{
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        _currentPinchZoomFactor = _kitCN.pinchZoomFactor;
    }
    CGFloat zoomFactor = _currentPinchZoomFactor * recognizer.scale;//当前触摸缩放因子*坐标比例
    [_kitCN setPinchZoomFactor:zoomFactor];
}

/**
 @abstract 将UI的坐标转换成相机坐标
 */
- (CGPoint)convertToPointOfInterestFromViewCoordinates:(CGPoint)viewCoordinates
{
    CGPoint pointOfInterest = CGPointMake(.5f, .5f);
    CGSize frameSize = self.view.frame.size;
    CGSize apertureSize = [_kitCN captureDimension];
    CGPoint point = viewCoordinates;
    CGFloat apertureRatio = apertureSize.height / apertureSize.width;
    CGFloat viewRatio = frameSize.width / frameSize.height;
    CGFloat xc = .5f;
    CGFloat yc = .5f;
    
    if (viewRatio > apertureRatio) {
        CGFloat y2 = frameSize.height;
        CGFloat x2 = frameSize.height * apertureRatio;
        CGFloat x1 = frameSize.width;
        CGFloat blackBar = (x1 - x2) / 2;
        if (point.x >= blackBar && point.x <= blackBar + x2) {
            xc = point.y / y2;
            yc = 1.f - ((point.x - blackBar) / x2);
        }
    }else {
        CGFloat y2 = frameSize.width / apertureRatio;
        CGFloat y1 = frameSize.height;
        CGFloat x2 = frameSize.width;
        CGFloat blackBar = (y1 - y2) / 2;
        if (point.y >= blackBar && point.y <= blackBar + y2) {
            xc = ((point.y - blackBar) / y2);
            yc = 1.f - (point.x / x2);
        }
    }
    pointOfInterest = CGPointMake(xc, yc);
    return pointOfInterest;
}


- (void)toast:(NSString*)message
{
    
    UIAlertView *toast = [[UIAlertView alloc] initWithTitle:nil
                                                    message:message
                                                   delegate:nil
                                          cancelButtonTitle:nil
                                          otherButtonTitles:nil, nil];
    [toast show];
    double duration = 2.5;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [toast dismissWithClickedButtonIndex:0 animated:NO];
    });
}

#pragma mark - GetMethod

- (UIView *)captureView
{
    if (!_captureView) {
        _captureView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
        _captureView.backgroundColor = [UIColor blackColor];
    }
    return _captureView;
}

- (UILabel *)stateLab
{
    if (!_stateLab) {
        _stateLab = [[UILabel alloc] initWithFrame:CGRectMake(0, Height-100, Width, 100)];
        _stateLab.backgroundColor = [UIColor clearColor];
        _stateLab.numberOfLines = 0;
        _stateLab.textColor = [UIColor redColor];
    }
    return _stateLab;
}

- (FilterFunctionView *)filterView
{
    if (!_filterView) {
        _filterView = [[FilterFunctionView alloc] initWithFrame:CGRectMake(0, 170, Width, 200)];
        _filterView.hidden = YES;
    }
    return _filterView;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CNLiveCaptureStateDidChangeNotification object:nil];
    
    self.kitCN = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end