LVCLiveViewController.m 22.7 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 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
//
//  LVCLiveViewController.m
//  LiveVideoCloud
//
//  Created by 张旭 on 2017/3/7.
//  Copyright © 2017年 cnlive. All rights reserved.
//

#import "LVCLiveViewController.h"
#import <CNLivePlayerSDK/CNLiveGPUStreamerKit.h>
#import <CNLivePlayerSDK/CNLiveWebcastManager.h>
#import "FilterFunctionView.h"
#import "LVCUGCLivePrepareView.h"
#import "LiveBaseView.h"
#import "LVCUGCLiveEndView.h"
#import "LVCVerifyLiveAuthService.h"
#import "LVCVerifyViewController.h"
#import "LoginViewController.h"

@interface LVCLiveViewController ()<UIGestureRecognizerDelegate, UIAlertViewDelegate, UINavigationControllerDelegate> {
    
    BOOL _isStreaming;
}

@property (nonatomic, strong) LVCUGCLivePrepareView *prepareView;

@property (nonatomic, strong) UIView *captureView;

@property (nonatomic, strong) CNLiveGPUStreamerKit *kitCN;

@property (nonatomic, strong) FilterFunctionView *filterView;

@property (nonatomic, strong) UIButton *quitButton;

@property (nonatomic, strong) UIButton *openFilterButton;

@property (nonatomic, strong) UIButton *changeCameraButton;

@property (nonatomic, strong) UIButton *openFlashButton;

@property (nonatomic ,strong) LiveBaseView * _Nullable liveBaseView;

@property (nonatomic, strong) LVCUGCLiveEndView *endView;

@end

@implementation LVCLiveViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.delegate = self;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self verifyLiveAuthority];
}

#pragma mark - 验证是否有主播权限
- (void)verifyLiveAuthority {
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD showWithStatus:@"正在加载..."];
    [LVCVerifyLiveAuthService verifyLiveAuthWithHandler:^(id data, NSError *error) {
        
        [SVProgressHUD dismiss];
        if (error) {
            NSLog(@"失败===>error:%@",error);
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"抱歉, 鉴权失败~ "] delegate:self cancelButtonTitle:@"好的" otherButtonTitles: nil];
            alert.tag = 1005;
            [alert show];
            
            return ;
        }
        
        NSLog(@"成功===>data:%@",data);
        
        int status = [data[@"status"] intValue];
        if (status == -1) {          //未审核
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"亲, 完成实名认证就可以开播啦,现在就去认证吧!" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去认证", nil];
            alert.tag = 1001;
            [alert show];
        } else if (status == 1) {    //审核中
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"亲, 正在审核中..." delegate:self cancelButtonTitle:@"好的" otherButtonTitles: nil];
            alert.tag = 1002;
            [alert show];
        } else if (status == 2) {   //审核失败
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"抱歉, 审核失败~" delegate:self cancelButtonTitle:@"好的" otherButtonTitles: nil];
            alert.tag = 1003;
            [alert show];
        } else if (status == 3) {   //启用
            //开始推流
            [self.view addSubview:self.captureView];
            [self.view addSubview:self.prepareView];
            [self.view addSubview:self.quitButton];
            [self.view addSubview:self.changeCameraButton];
            [self.view addSubview:self.openFilterButton];
            [self.view addSubview:self.openFlashButton];
            [self.view addSubview:self.filterView];
            
            // 初始化推流
            // 生成随机活动号
            NSInteger time = [[NSDate date] timeIntervalSince1970];
            NSString *timeString = [NSString stringWithFormat:@"%ld", (long)time];
            NSString *random = [NSString stringWithFormat:@"%d%d%d%d%d",arc4random()%9,arc4random()%9,arc4random()%9,arc4random()%9,arc4random()%9];
            NSString *activityId = [NSString stringWithFormat:@"%@%@",timeString,random];
        
//            _kitCN = [[CNLiveGPUStreamerKit alloc] initWithDefaultConfigWithActivityId:activityId channelId:@"iOStest" isHorizontalScreen:@"0"];
            
            _kitCN = [[CNLiveGPUStreamerKit alloc] initCNLiveKitWithInterruptConfigWithPureAudioMode:NO];
            _kitCN.activityId = activityId;
            _kitCN.channelId = data[@"channelId"];
            
            // 主播ID
            NSString *channelName = data[@"channelName"];
            NSString *coverImgUrl = data[@"coverImgUrl"];

            // 封面图
            _kitCN.coverImgUrl =  coverImgUrl;
            // 昵称  头像
            NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:channelName, @"name", [UserInformationModel manager].faceUrl, @"iconUrl", nil];
            _kitCN.extensions = [self dictionaryToJson:userInfo];
        
            // 设置推流配置
            [self setStreamerCfg];
        
            [self addObservers];
        
            UITapGestureRecognizer * singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTap:)];
            singleRecognizer.delegate = self;
            [self.captureView addGestureRecognizer:singleRecognizer];
            
        } else {   //禁用
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"抱歉, 您没有权限~" delegate:self cancelButtonTitle:@"好的" otherButtonTitles: nil];
            alert.tag = 1004;
            [alert show];
        }

    }];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (alertView.tag == 1001 && buttonIndex == 1) {  // 未审核 去认证
        
        NSLog(@"未审核 去认证");
        LVCVerifyViewController *vc = [[LVCVerifyViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    } else {
        
        NSLog(@"弹出");
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    BOOL isHomePage = [viewController isKindOfClass:[self class]];
    
    [self.navigationController setNavigationBarHidden:isHomePage animated:YES];
}

#pragma mark - initialization Streamer
- (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];
    
}

- (LiveBaseView *)liveBaseView
{
    if (!_liveBaseView)
    {
        _liveBaseView = [LiveBaseView liveBaseView];
        _liveBaseView.jumpType = JumpControllerTypePresent;
        _liveBaseView.viewController = self;
        _liveBaseView.backgroundColor = [UIColor clearColor];
        [_liveBaseView.closeBtn addTarget:self action:@selector(quitBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _liveBaseView;
}

#pragma mark - UIButton Action  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- (void)startCapture:(UIButton *)button {   // 开始推流

    // 设置标题
    if (_prepareView.titleTextField.text) {
        _kitCN.activityName = _prepareView.titleTextField.text;
    } else {
        _kitCN.activityName = @"主播很懒,没有标题~";
    }
    
    [_openFilterButton removeFromSuperview];
    [_changeCameraButton removeFromSuperview];
    [_openFlashButton removeFromSuperview];
    _openFilterButton = nil;
    _changeCameraButton = nil;
    _openFlashButton = nil;

    [_prepareView removeFromSuperview];
    
    [_kitCN startStream:^{
        NSLog(@"开启推流成功 ------- success");
        
        _isStreaming = YES;
        [_quitButton removeFromSuperview];
        [self.view insertSubview:self.liveBaseView atIndex:1];
        [self.liveBaseView.animationBaseView addSubview:self.openFilterButton];
        [self.liveBaseView.animationBaseView addSubview:self.changeCameraButton];
        [self.liveBaseView.animationBaseView addSubview:self.openFlashButton];
        
    } failure:^(NSDictionary *errorDic) {
        //NSString *str=[[NSMutableString alloc] initWithData:errorDic[@"errorMessage"] encoding:NSUTF8StringEncoding];
        NSLog(@"%@",errorDic);
        [self toast:errorDic[@"errorMessage"]];
    }];
}


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


- (void)changeCamera:(UIButton *)button {   // 转换前后置摄像头
    
    button.selected = !button.selected;
    _openFlashButton.hidden = !_openFlashButton.hidden;
//        if (button.selected) {
//            _kitCN.cameraPosition = AVCaptureDevicePositionBack;
//        }else{
//            _kitCN.cameraPosition = AVCaptureDevicePositionFront;
//        }
    [_kitCN switchCamera];
    
}


- (void)openFlash:(UIButton *)button {   // 闪光灯
    
    button.selected = !button.selected;
    [_kitCN toggleTorch];
    //    [_kitCN setTorchMode:AVCaptureTorchModeOn];
}


- (void)quitBtnClick {    // 退出
    
    if (_isStreaming) {
        [self.view addSubview:self.endView];
    } else {
        if (_kitCN.captureState == CNLiveCaptureStateCapturing) {
            [_kitCN stopPreview];
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)continueButtonClick {
    
    [_endView removeFromSuperview];
}

- (void)endButtonClick {
    
    if (_kitCN.streamState == CNLiveStreamStateConnected) {
        [_kitCN stopStream];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - UIGestureRecognizer Action !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- (void)onTap:(UIGestureRecognizer *)sender {  //对焦与曝光
    
    CGPoint current = [sender locationInView:self.view];
    CGPoint point = [self convertToPointOfInterestFromViewCoordinates:current];
    [_kitCN exposureAtPoint:point];
    [_kitCN focusAtPoint:point];
    
    if ([_prepareView.titleTextField isFirstResponder]) {
        [_prepareView.titleTextField resignFirstResponder];
    }
}

#pragma mark - notification  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- (void)enterBg {   // 进入后台
    
    [_kitCN appEnterBackground];
}

- (void)becameActive {   // 回到前台
    
    [_kitCN appBecomeActive];
}

- (void)captureStateChange {   // 采集状态改变
    
    if ( _kitCN.captureState == CNLiveCaptureStateIdle){
        //初始化时状态为空闲
        NSLog(@"---------CNLiveCaptureStateIdle");
        return;
    }
    else if (_kitCN.captureState == CNLiveCaptureStateCapturing ) {
        //设备工作中
        NSLog(@"---------CNLiveCaptureStateCapturing");
        return;
    }
    else if (_kitCN.captureState == CNLiveCaptureStateClosingCapture ) {
        //关闭采集设备中
        NSLog(@"---------CNLiveCaptureStateClosingCapture");
        return;
    }
    else if (_kitCN.captureState == CNLiveCaptureStateDevAuthDenied ) {
        //设备授权被拒绝
        NSLog(@"---------CNLiveCaptureStateDevAuthDenied");
        [self toast:@"设备未授权,请授权~"];
        
        return;
    }
    else if (_kitCN.captureState == CNLiveCaptureStateParameterError ) {
        // 参数错误,无法打开
        NSLog(@"---------CNLiveCaptureStateParameterError");
        
        return;
    }
    else if (_kitCN.captureState == CNLiveCaptureStateDevBusy ) {
        //设备正忙,请稍后尝试
        NSLog(@"---------CNLiveCaptureStateDevBusy");
        
    }
}

- (void)streamStateChange {   // 推流状态改变
    
    if (_kitCN.streamState == CNLiveStreamStateIdle) {
        
        NSLog(@"---------CNLiveStreamStateIdle");
    }
    
    if (_kitCN.streamState == CNLiveStreamStateConnecting) {
        
        NSLog(@"---------CNLiveStreamStateConnecting");
    }
    
    if (_kitCN.streamState == CNLiveStreamStateConnected) {
        
        NSLog(@"---------CNLiveStreamStateConnected");
    }
    
    //断开推流中
    if ( _kitCN.streamState == CNLiveStreamStateDisconnecting) {
        
        NSLog(@"---------CNLiveStreamStateDisconnecting");
    }
    
    //结束推流成功
    if ( _kitCN.streamState == CNLiveStopStreamSuccess) {
        
        NSLog(@"---------CNLiveStopStreamSuccess");
    }
    
    //结束推流失败
    if ( _kitCN.streamState == CNLiveStopStreamFailure) {
        
        NSLog(@"---------CNLiveStopStreamFailure");
    }
    
    //推流出错
    if (_kitCN.streamState == CNLiveStreamStateError) {
        
        NSLog(@"---------CNLiveStreamStateError");
        [self onStreamError];
    }
    
}

- (void)onStreamError {   // 推流失败
    
    CNLiveStreamErrorCode err = _kitCN.streamErrorCode;
    
    NSLog(@"onErr: %lu ", (unsigned long) err);
    
    if ( CNLiveStreamErrorCode_CNLiveAUTHFAILED == err ) {
        
    }
    else if ( CNLiveStreamErrorCode_CODEC_OPEN_FAILED == err) {
        
    }
    else if ( CNLiveStreamErrorCode_CONNECT_FAILED == err) {

    }
    else if ( CNLiveStreamErrorCode_CONNECT_BREAK == err) {

    }
    else if ( CNLiveStreamErrorCode_ABNORMAL == err) {

        [self toast:@"推流异常中断~~"];
        [self tryReconnect];
        
    } 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];
        
        [_kitCN startStream:^{
            NSLog(@"重试开启推流成功 ------- success");
            
        } failure:^(NSDictionary *errorDic) {
            [self toast:errorDic[@"errorMessage"]];
        }];
        
    });
}


- (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];
    });
}


- (CGPoint)convertToPointOfInterestFromViewCoordinates:(CGPoint)viewCoordinates {// 将UI的坐标转换成相机坐标
    
    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;
}

#pragma mark - GetMethod   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

- (LVCUGCLivePrepareView *)prepareView {
    
    if (!_prepareView) {
        _prepareView = [[LVCUGCLivePrepareView alloc] initWithFrame:self.view.bounds];
        [_prepareView.startButton addTarget:self action:@selector(startCapture:) forControlEvents:UIControlEventTouchUpInside];
        UITapGestureRecognizer * tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTap:)];
        tapRecognizer.delegate = self;
        [_prepareView addGestureRecognizer:tapRecognizer];
    }
    return _prepareView;
}

- (FilterFunctionView *)filterView
{
    if (!_filterView) {
        _filterView = [[FilterFunctionView alloc] initWithFrame:CGRectMake(0, 75, SCREEN_WIDTH, 200)];
        _filterView.hidden = YES;
    }
    return _filterView;
}

- (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;
}

- (UIButton *)quitButton {
    
    if (!_quitButton) {
        _quitButton = [self createButtonWithFrame:CGRectMake(SCREEN_WIDTH - 50, 30, 35, 35) image:@"LiveCloseNormal" selected:@"LiveCloseTouch"];
        [_quitButton addTarget:self action:@selector(quitBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _quitButton;
}

- (UIButton *)changeCameraButton {
    
    if (!_changeCameraButton) {
        _changeCameraButton = [self createButtonWithFrame:CGRectMake(SCREEN_WIDTH - 100, 30, 35, 35) image:@"camera" selected:@"Select the camera"];
        [_changeCameraButton addTarget:self action:@selector(changeCamera:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _changeCameraButton;
}

- (UIButton *)openFlashButton {
    
    if (!_openFlashButton) {
        _openFlashButton = [self createButtonWithFrame:CGRectMake(SCREEN_WIDTH - 100, 75, 35, 35) image:@"open flash" selected:@"Flash off"];
        _openFlashButton.hidden = YES;
        [_openFlashButton addTarget:self action:@selector(openFlash:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _openFlashButton;
}

- (UIButton *)openFilterButton {
    
    if (!_openFilterButton) {
        _openFilterButton = [self createButtonWithFrame:CGRectMake(SCREEN_WIDTH - 150, 30, 35, 35) image:@"Is closed" selected:@"Is open"];
        [_openFilterButton addTarget:self action:@selector(openFilter:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _openFilterButton;
}

- (LVCUGCLiveEndView *)endView {
    
    if (!_endView) {
        _endView = [[LVCUGCLiveEndView alloc] initWithFrame:CGRectMake(20, SCREEN_HEIGHT * 0.3, SCREEN_WIDTH - 40, SCREEN_WIDTH - 40)];
        _endView.layer.cornerRadius = 20;
        _endView.layer.masksToBounds = YES;
        [_endView.continueButton addTarget:self action:@selector(continueButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [_endView.endButton addTarget:self action:@selector(endButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _endView;
}

#pragma mark - Action !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

- (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];
}

- (UIButton *)createButtonWithFrame:(CGRect)frame image:(NSString *)image selected:(NSString *)selected {
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:frame];
    [btn setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:selected] forState:UIControlStateSelected];
    return btn;
}

- (NSString *)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    // 序列化
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

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

@end