CNLiveStreamerKit.m 49.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 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 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 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 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 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 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
//
//  CNLiveStreamerKit.m
//  CNLivePlayer_Example
//
//  Created by CNLive-zxw on 2019/8/20.
//  Copyright © 2019 153993236@qq.com. All rights reserved.
//

#import "CNLiveStreamerKit.h"
#import "GCDAsyncSocket.h"
#import <CNLiveMsgTools/CNLiveMsgManager.h>

#import "CNLiveStreamerManager.h"
#import "CNLiveWatermark.h"
#import "CNLiveStreamerBase.h"
#import "CNLiveAudioCapture.h"
#import "CNLiveBeautifyFaceFilter.h"
#import "CNLiveBgmPlayer.h"
#import "CNLivePlayerManager.h"
#import "CNLiveStreamerTools.h"
#import "CNLivePlayerNetworkManager.h"

#import "CNLiveStreamerUrl.h"

#define Host @"bc.cnlive.com"
#define Port 65432

//采集状态通知
NSString * const CNLiveCaptureStateDidChangeNotification = @"CNLiveCaptureStateDidChangeNotification";

//推流状态通知
NSString * const CNLiveStreamerStateDidChangeNotification = @"CNLiveStreamerStateDidChangeNotification";

//自动重连失败通知
NSString * const CNLiveStreamerReconnectStatusChangedNotification = @"CNLiveStreamerReconnectStatusChangedNotification";

//获取直播时长通知
NSString * const CNLiveStreamerGetDurationNotification = @"CNLiveStreamerGetDurationNotification";

//收到消息通知
NSString * const CNLiveStreamerMsgReceiveNotification = @"CNLiveMsgToolsPlayerReceiveNotification";

//由服务端断开
NSString * const CNLiveServiceConnectBreakNotification = @"CNLiveServiceConnectBreakNotification";

@interface CNLiveStreamerKit()<GCDAsyncSocketDelegate> {
    BOOL _isRecording;          //是否正在直播
    BOOL _activitySuccess;      //活动是否创建成功
    BOOL _isCNLiveStreaming;    //是否为视讯云平台推流
    
    BOOL _pureAudioMode;        //是否为纯音频推流
    
    int  _autoRetryCnt;         //记录重试次数
    BOOL _retryFailed;          //重连失败
    BOOL _reteying;             //是否处于重试中
    BOOL _initiativeRetry;      //用户主动重试
    
    BOOL _registerChatNoti;     //记录是否已经注册了聊天室通知
    NSString *_contentId;
    NSString *_roomId;
    int _originalStatus;        //原始状态
    
    CNLiveStreamerManager *_manager;
    
    BOOL _enterBackground;
}

@property (nonatomic, strong) GPUImageFilter *filter;                           //美颜(用于默认美颜)
@property (nonatomic, strong) NSURL *hostURL;                                   //推流地址
@property (nonatomic, strong) NSMutableDictionary *parameter;                   //存储直播活动相关信息
@property (nonatomic, strong) GCDAsyncSocket *socket;                           //socket用于向服务器发送消息(30s一次)
@property (nonatomic, retain) NSTimer *heartTimer;                              //心跳定时器

@property (nonatomic, strong) CNLiveWatermark *watermark;                       //水印
@property (nonatomic, strong) CNLiveStreamerBase *streamerBase;                 //推流
@property (nonatomic, strong) CNLiveAudioCapture *audioCapture;                 //音频采集
@property (nonatomic, strong) CNLiveBeautifyFaceFilter *beautifyFaceFilter;     //美颜
@property (nonatomic, strong) CNLiveBgmPlayer *bgmPlayer;                       //背景音乐

@end

@implementation CNLiveStreamerKit
#pragma mark - 初始化方法
/**
 @abstract      纯音频推流初始化(不会打断其他后台的音乐播放)
 @warning       实例化的对象必须赋值给一个全局变量
 @warning       必传参数
 */
- (instancetype)initPureAudioStreamerWithDefaultConfig{
    if (self = [super init]) {
        _logPrintEnable = YES;
        _pureAudioMode = YES;
        _autoRetryCnt = 0;
        _autoRetryDelay = 2.0;
        
        _parameter = [[NSMutableDictionary alloc] init];
        [self setStreamerWithConfig:NO];
        
        //视讯云直播,注册前后台切换通知
        [self addStatusChangedObservers];
        
    }
    return self;
}

/**
 @abstract      纯音频推流初始化(会打断其他后台的音乐播放)
 @warning       实例化的对象必须赋值给一个全局变量
 @warning       必传参数
 */
- (instancetype)initPureAudioStreamerWithInterruptConfig{
    if (self = [super init]) {
        _logPrintEnable = YES;
        _pureAudioMode = YES;
        _autoRetryCnt = 0;
        _autoRetryDelay = 2.0;
        
        _parameter = [[NSMutableDictionary alloc] init];
        [self setStreamerWithConfig:NO];
        
        //视讯云直播,注册前后台切换通知
        [self addStatusChangedObservers];
        
    }
    return self;
}

/**
 @abstract      音视频推流初始化(不会打断其他后台的音乐播放)
 @warning       实例化的对象必须赋值给一个全局变量
 @warning       必传参数
 */
- (instancetype)initVodStreamerWithDefaultConfig{
    if (self = [super init]) {
        _logPrintEnable = YES;
        _pureAudioMode = NO;
        _autoRetryCnt = 0;
        _autoRetryDelay = 2.0;
        
        _parameter = [[NSMutableDictionary alloc] init];
        [self setStreamerWithConfig:NO];
        
        //视讯云直播,注册前后台切换通知
        [self addStatusChangedObservers];
        
    }
    return self;
}

/**
 @abstract      音视频推流初始化(会打断其他后台的音乐播放)
 @warning       实例化的对象必须赋值给一个全局变量
 @warning       必传参数
 */
- (instancetype)initVodStreamerWithInterruptConfig{
    if (self = [super init]) {
        _logPrintEnable = YES;
        _pureAudioMode = NO;
        _autoRetryCnt = 0;
        _autoRetryDelay = 2.0;
        
        _parameter = [[NSMutableDictionary alloc] init];
        [self setStreamerWithConfig:NO];
        
        //视讯云直播,注册前后台切换通知
        [self addStatusChangedObservers];
        
    }
    return self;
}

//普通推流
//不会打断其他后台音乐
- (instancetype)initWithDefaultConfig:(BOOL)pureAudioMode {
    if (self = [super init]) {
        _logPrintEnable = YES;
        _pureAudioMode = pureAudioMode;
        [self setStreamerWithConfig:NO];
    }
    return self;
}

//会打断其他后台音乐
- (instancetype)initWithInterruptConfig:(BOOL)pureAudioMode {
    if (self = [super init]) {
        _logPrintEnable = YES;
        _pureAudioMode = pureAudioMode;
        [self setStreamerWithConfig:YES];
    }
    return self;
}

#pragma mark - 初始化推流器
- (void)setStreamerWithConfig:(BOOL)interrupt {
    _manager = [CNLiveStreamerManager manager];
    
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    
    //初始化金山kit
    if (interrupt) {
        _manager.kit = [[KSYGPUStreamerKit alloc] initWithInterruptCfg];
    }
    else {
        _manager.kit = [[KSYGPUStreamerKit alloc] initWithDefaultCfg];
    }
    
    //是否为纯音频推流
    if (_pureAudioMode) {
        [_manager.kit.aCapDev startCapture];
        _manager.kit.streamerBase.bWithVideo = NO;
        
    }
    else {
        //设置初始美颜
        _filter = [[KSYGPUBeautifyExtFilter alloc] init];
        [(KSYGPUBeautifyExtFilter *)_filter setBeautylevel: 0.5];
        [_manager.kit setupFilter:_filter];
        
        //摄像头位置
        _manager.kit.cameraPosition = AVCaptureDevicePositionFront;
    }
    
    _manager.kit.streamerBase.shouldEnableKSYStatModule = NO;   //收集网络相关状态的日志(不收集)
    _manager.kit.videoProcessingCallback = ^(CMSampleBufferRef sampleBuffer){
        
    };
    
    _manager.kit.audioProcessingCallback = ^(CMSampleBufferRef buf){
        
    };
    
    //添加通知
    [self addKSYObservers];
    
}

#pragma mark - 通知
- (void)addKSYObservers {
    //采集状态通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onCaptureStateChange)
                                                 name:KSYCaptureStateDidChangeNotification
                                               object:nil];
    //推流状态通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onStreamStateChange)
                                                 name:KSYStreamStateDidChangeNotification
                                               object:nil];
    
    
}

//前后台切换通知
- (void)addStatusChangedObservers {
    
    if (_isCNLiveStreaming) return;
    
    _isCNLiveStreaming = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(enterBackground)
                                                 name:UIApplicationWillResignActiveNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(enterForeground)
                                                 name:UIApplicationDidBecomeActiveNotification
                                               object:nil];
}

- (void)onCaptureStateChange {
    _captureState = (CNLiveCaptureState)_manager.kit.captureState;
    
    if (self.logPrintEnable) {
        NSLog(@"CNLiveStreamerKit-->采集设备工作状态CNLiveCaptureState:%ld", (unsigned long)self.captureState);
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveCaptureStateDidChangeNotification
                                                        object:nil
                                                      userInfo:nil];
}

- (void)onStreamStateChange {
    //推流状态发生改变时通知开发者
    if (_manager.kit.streamerBase.streamState == KSYStreamStateError) {
        _streamErrorCode = (CNLiveStreamErrorCode)_manager.kit.streamerBase.streamErrorCode;
    }
    _streamState = (CNLiveStreamState)_manager.kit.streamerBase.streamState;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveStreamerStateDidChangeNotification
                                                        object:nil
                                                      userInfo:nil];
    
    if (_manager.kit.streamerBase.streamState == KSYStreamStateConnected) {  //连接成功恢复连接次数最大值
        
        if (_autoRetryCnt < 3) {
            _reconnectStatus = CNLiveReconnectStatusSuccess;
            [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveStreamerReconnectStatusChangedNotification
                                                                object:nil
                                                              userInfo:nil];
            [self recoverReconnectConfig];
        }
        _autoRetryCnt = _maxAutoRetry;
    }
    
    //推流出错
    if (_manager.kit.streamerBase.streamState == KSYStreamStateError && _isCNLiveStreaming) {
        _isRecording = NO;
        
        [CNLiveStreamerTools getRealTimeString:^(NSString *timeString) {
            [self requestStopStreamerWithInfo:[NSString stringWithFormat:@"KSY error:%@",[_manager.kit.streamerBase getKSYStreamErrorCodeName:_manager.kit.streamerBase.streamErrorCode]] timeString:timeString];
        }];
        
        [CNLiveStreamerTools errorStat:@"推流出错"  activityId:_activityId];
        
        //重连失败通知开发者
        if (_retryFailed && _isCNLiveStreaming) {
            
            _reconnectStatus = CNLiveReconnectStatusFailed;
            [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveStreamerReconnectStatusChangedNotification
                                                                object:nil
                                                              userInfo:nil];
            [self recoverReconnectConfig];
        }
        
        //以下为视讯云平台重连情况
        if (_isCNLiveStreaming) {
            if (_manager.kit.streamerBase.streamErrorCode == KSYStreamErrorCode_CONNECT_BREAK ||
                _manager.kit.streamerBase.streamErrorCode == KSYStreamErrorCode_AV_SYNC_ERROR ||
                _manager.kit.streamerBase.streamErrorCode == KSYStreamErrorCode_Connect_Server_failed ||
                _manager.kit.streamerBase.streamErrorCode == KSYStreamErrorCode_DNS_Parse_failed ||
                _manager.kit.streamerBase.streamErrorCode == KSYStreamErrorCode_CODEC_OPEN_FAILED) {
                
                if (_autoRetryCnt>0 && !_initiativeRetry) {
                    [self tryReconnect];
                    
                }
            }
            
        }
        
        if (self.logPrintEnable) {
            NSLog(@"CNLiveGPUStreamerKit-->推流出错CNLiveStreamErrorCode error:%ld", (unsigned long)self.streamErrorCode);
        }
        
    } else if ( _manager.kit.streamerBase.streamState == KSYStreamStateDisconnecting) {//断开推流
        
        if (![CNLiveStreamerTools isEmptyString:PLAYER_AppID] && _enterBackground == NO && _isRecording) {
            _streamErrorCode = CNLiveStreamErrorCode_ABNORMAL;
            _streamState = CNLiveStreamStateError;
            [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveStreamerStateDidChangeNotification
                                                                object:nil
                                                              userInfo:nil];
            
            [CNLiveStreamerTools getRealTimeString:^(NSString *timeString) {
                [self requestStopStreamerWithInfo:@"CNLiveStreamErrorCode_ABNORMAL_2" timeString:timeString];
            }];
            
            _isRecording = NO;
            if (self.logPrintEnable) {
                NSLog(@"CNLiveGPUStreamerKit-->推流出错CNLiveStreamErrorCode error:%ld", (unsigned long)self.streamErrorCode);
            }
        }
    } else {
        
    }
    
    NSLog(@"CNLiveGPUStreamerKit-->推流工作状态发生变化CNLiveStreamState:%ld", (unsigned long)self.streamState);
    
}

- (void)enterBackground {
    /**
     *  视讯云平台:推流过程中退到后台或者锁屏情况下,需将活动状态改为“-2”,以便观众端收到主播离开的消息
     */
    if (!_activitySuccess) return;
    _enterBackground = YES;
    [_manager.kit.streamerBase stopStream];
    
    __block UIBackgroundTaskIdentifier task;
    task = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication] endBackgroundTask:task];
    }];
    
    [CNLiveStreamerTools getRealTimeString:^(NSString *timeString) {
        [self requestStopStreamerWithInfo:@"CNLiveStreamErrorCode_EnterBackground" timeString:timeString];
        
    }];
}

- (void)enterForeground {
        
    if (!_activitySuccess) return;
    _enterBackground = NO;
    
    /**
     *  视讯云平台:APP返回前台重新将活动状态改为“1”,若失败将推流状态改为error,并通知开发者
     */
    [CNLiveStreamerTools getRealTimeString:^(NSString *timeString) {
        [self requestStartStreamer:NULL failure:^(NSDictionary *errorDic) {

            _streamErrorCode = CNLiveStreamErrorCode_ABNORMAL;
            _streamState = CNLiveStreamStateError;

            [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveStreamerStateDidChangeNotification
                                                                object:nil
                                                              userInfo:nil];
        } timeString:timeString];
    }];
}


- (void)quitStreaming {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:KSYCaptureStateDidChangeNotification
                                                  object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:KSYStreamStateDidChangeNotification
                                                  object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIApplicationWillResignActiveNotification
                                                  object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIApplicationDidBecomeActiveNotification
                                                  object:nil];
    
    
    [self.heartTimer invalidate];
    self.heartTimer = nil;
    
    [_manager destroyStreamerManager];
    _manager = nil;
    
}

#pragma mark - capture
//采集分辨率
- (void)setCapPreset:(NSString *)capPreset {
    _manager.kit.capPreset = capPreset;
    _capPreset = capPreset;
}

//查询实际的采集分辨率
- (CGSize)captureDimension {
    return [_manager.kit captureDimension];
}

//预览分辨率
- (void)setPreviewDimension:(CGSize)previewDimension {
    _manager.kit.previewDimension = previewDimension;
    _previewDimension = previewDimension;
}

//推流分辨率
- (void)setStreamDimension:(CGSize)streamDimension {
    _manager.kit.streamDimension = streamDimension;
    _streamDimension = streamDimension;
}

//视频帧率
- (void)setVideoFPS:(int)videoFPS {
    _manager.kit.videoFPS = videoFPS;
    _videoFPS = videoFPS;
}

//摄像头位置
- (void)setCameraPosition:(AVCaptureDevicePosition)cameraPosition {
    _manager.kit.cameraPosition = cameraPosition;
    _cameraPosition = cameraPosition;
}

//摄像头朝向
-(void)setVideoOrientation:(UIInterfaceOrientation)orientation {
    _manager.kit.videoOrientation = orientation;
}

#pragma mark -  mirror & rotate
//预览设置成镜像模式
- (void)setPreviewMirrored:(BOOL)previewMirrored {
    _manager.kit.previewMirrored = previewMirrored;
    _previewMirrored = previewMirrored;
}

//推流设置成镜像模式
- (void)setStreamerMirrored:(BOOL)streamerMirrored {
    _manager.kit.streamerMirrored = streamerMirrored;
    _streamerMirrored = streamerMirrored;
}

//旋转预览视图
- (void)rotatePreviewTo:(UIInterfaceOrientation)orie {
    [_manager.kit rotatePreviewTo:orie];
}

//旋转推流画面
- (void)rotateStreamTo:(UIInterfaceOrientation)orie {
    [_manager.kit rotateStreamTo:orie];
}

#pragma mark - camera operation
- (BOOL)switchCamera {
    return  [_manager.kit switchCamera];
}

- (BOOL)isTorchSupported {
    return [_manager.kit isTorchSupported];
}

- (AVCaptureDevice *)getCurrentCameraDevices {
    return [_manager.kit getCurrentCameraDevices];
}

//设置闪光灯
- (void)setTorchMode:(AVCaptureTorchMode)mode {
    [_manager.kit setTorchMode:mode];
}

//闪光灯切换
- (void)toggleTorch {
    [_manager.kit toggleTorch];
}

#pragma mark - reconnect(由于开启会暴露推流地址,暂不开放)
@synthesize maxAutoRetry = _maxAutoRetry;
- (void)setMaxAutoRetry:(int)maxAutoRetry {
    if (_isCNLiveStreaming) {
        _maxAutoRetry = MAX(0, maxAutoRetry);
        _autoRetryCnt = _maxAutoRetry;
    } else {
        _manager.kit.maxAutoRetry = maxAutoRetry;
    }
}

@synthesize autoRetryDelay = _autoRetryDelay;
- (void)setAutoRetryDelay:(double)autoRetryDelay {
    if (_isCNLiveStreaming) {
        _autoRetryDelay = MAX(0.1, autoRetryDelay);
        _manager.kit.autoRetryDelay = autoRetryDelay;
    } else {
        _manager.kit.autoRetryDelay = autoRetryDelay;
    }
}

- (void)tryReconnect {
    
    if (_autoRetryCnt < 1) {
        return;
    }
    
    if (_reteying == YES) {
        return;
    }
    
    _reteying = YES;
    
    if (_autoRetryCnt == _maxAutoRetry) {
        _reconnectStatus = CNLiveReconnectStatusStart;
        [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveStreamerReconnectStatusChangedNotification
                                                            object:nil
                                                          userInfo:nil];
    }
    
    int64_t delaySec = (int64_t)(_autoRetryDelay * NSEC_PER_SEC);
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, delaySec);
    dispatch_after(delay, dispatch_get_main_queue(), ^{
        
        if (!_manager.kit.streamerBase.isStreaming) {
            
            if (_logPrintEnable) {
                NSLog(@"CNLiveGPUStreamerKit-->第(%d)次重连/(%d)", (_maxAutoRetry-_autoRetryCnt+1),_maxAutoRetry);
            }
            [CNLiveStreamerTools getRealTimeString:^(NSString *timeString) {
                [self requestStartStreamer:NULL failure:NULL timeString:timeString];
            }];
            
            _autoRetryCnt--;
            if (_autoRetryCnt == 0) {
                _retryFailed = YES;
            }
        }
    });
}

- (void)recoverReconnectConfig {
    _retryFailed = NO;
}

#pragma mark - KSYMethod
- (UIView *)preview {
    return (UIView *)_manager.kit.preview;
}

//启动预览
- (void)startPreview:(UIView *)view {
    [_manager.kit startPreview:view];
}

//关闭预览
- (void)stopPreview {
    [_manager.kit stopPreview];
}

//开启推流(鉴权)
- (void)startStream:(void (^)(void))successBlock failure:(void (^)(NSDictionary *))failureBlock {
    //若活动创建成功,直接开启活动
    if (_activitySuccess) {
        /**
         *  手动重新开始推流,将重连次数还原;手动重连:YES
         */
        _autoRetryCnt = _maxAutoRetry;
        _initiativeRetry = YES;
        _reteying = NO;
        _retryFailed = NO;
        
        [CNLiveStreamerTools getRealTimeString:^(NSString *timeString) {
            [self requestStartStreamer:successBlock failure:failureBlock timeString:timeString];
        }];
        
    } else {
        
        [CNLiveStreamerTools getRealTimeString:^(NSString *timeString) {
            [self createActivityWithSuccess:successBlock failure:failureBlock timeString:timeString];
        }];
        
    }
}

- (void)startStreamWithUrl:(NSString *)url activityId:(NSString *)activityId success:(void (^)(void))successBlock failure:(void (^)(NSDictionary *))failureBlock {
    _activitySuccess = YES;     //后台已创建活动,_activitySuccess为YES
    /**
     *  手动重新开始推流,将重连次数还原;手动重连:YES
     */
    _autoRetryCnt = _maxAutoRetry;
    _initiativeRetry = YES;
    _reteying = NO;
    _retryFailed = NO;
    
    _activityId = activityId;               //开发者传入的活动ID
    _hostURL = [NSURL URLWithString:url];   //推流地址
    
    [CNLiveStreamerTools getRealTimeString:^(NSString *timeString) {
        [self requestStartStreamer:successBlock failure:failureBlock timeString:timeString];
    }];
}

- (void)pauseStreaming {
    [_manager.kit.streamerBase stopStream];
    _isRecording = NO;
    [CNLiveStreamerTools getRealTimeString:^(NSString *timeString) {
        [self requestStopStreamerWithInfo:@"User Pause" timeString:timeString];
    }];
}

//开启推流(普通)
- (void)startStream:(NSURL *)hostURL {
    [_manager.kit.streamerBase startStream:hostURL];
}

//停止推流
- (void)stopStream {
    if (_activitySuccess) {
        [CNLiveStreamerTools getRealTimeString:^(NSString *timeString) {
            [self requestStopStreamerWithInfo:@"" timeString:timeString];
        }];
        _isRecording = NO;
        [self.socket disconnect];
        
        //断开RM连接
        [self quitRM];
    }
    
    [_manager.kit.streamerBase stopStream];
}

- (void)startRecordWithFilePath:(NSString *)path {
    [_manager.kit.streamerBase startStream:[NSURL URLWithString:path]];
}

- (void)stopRecord {
    [_manager.kit.streamerBase stopStream];
}

//进入后台
- (void)appEnterBackground {
    [_manager.kit appEnterBackground];
    
}

//回到前台
- (void)appBecomeActive {
    [_manager.kit appBecomeActive];
}

//自动变焦
- (void)focusAtPoint:(CGPoint)point {
    [_manager.kit focusAtPoint:point];
}

//自动曝光
- (void)exposureAtPoint:(CGPoint)point {
    [_manager.kit exposureAtPoint:point];
}

//缩放
- (void)setPinchZoomFactor:(CGFloat)pinchZoomFactor {
    _manager.kit.pinchZoomFactor = pinchZoomFactor;
}

- (CGFloat)pinchZoomFactor {
    return _manager.kit.pinchZoomFactor;
}

- (void)setStabilizationMode:(AVCaptureVideoStabilizationMode)stabilizationMode {
    _manager.kit.stabilizationMode = stabilizationMode;
}

#pragma mark - filters
- (void)setupFilter:(GPUImageOutput<GPUImageInput> *)filter {
    [_manager.kit setupFilter:filter];
}

#pragma mark - 设置接口参数
- (void)setActivityId:(NSString *)activityId {
    _activityId = [NSString stringWithFormat:@"%@", activityId];
    [_parameter setObject:[NSString stringWithFormat:@"%@", activityId] forKey:@"activityId"];
}

- (void)setChannelId:(NSString *)channelId {
    _contentId = channelId;
    [_parameter setObject:[NSString stringWithFormat:@"%@", channelId] forKey:@"channelId"];
}

- (void)setIsHorizontalScreen:(BOOL)isHorizontalScreen {
    _isHorizontalScreen = isHorizontalScreen;
    [_parameter setObject:isHorizontalScreen ? @"1" :@"0" forKey:@"isHorizontalScreen"];
}

- (void)setActivityName:(NSString *)activityName {
    _activityName = activityName;
    [_parameter setObject:[NSString stringWithFormat:@"%@", activityName] forKey:@"activityName"];
}

- (void)setActivityStatus:(NSString *)activityStatus {
    _activityStatus = activityStatus;
    [_parameter setObject:[NSString stringWithFormat:@"%@", activityStatus] forKey:@"activityStatus"];
}

- (void)setStartTime:(NSString *)startTime {
    _startTime = startTime;
    [_parameter setObject:[NSString stringWithFormat:@"%@", startTime] forKey:@"startTime"];
}

- (void)setEndTime:(NSString *)endTime {
    _endTime = endTime;
    [_parameter setObject:[NSString stringWithFormat:@"%@", endTime] forKey:@"endTime"];
}

- (void)setCoverImgUrl:(NSString *)coverImgUrl {
    _coverImgUrl = coverImgUrl;
    [_parameter setObject:[NSString stringWithFormat:@"%@", coverImgUrl] forKey:@"coverImgUrl"];
}

- (void)setActivityCategory:(NSString *)activityCategory {
    _activityCategory = activityCategory;
    [_parameter setObject:[NSString stringWithFormat:@"%@", activityCategory] forKey:@"activityCategory"];
}

- (void)setExtensions:(NSString *)extensions {
    _extensions = extensions;
    [_parameter setObject:[NSString stringWithFormat:@"%@", extensions] forKey:@"extensions"];
}

- (void)setCallbackAcitvityStatushttpPostUrl:(NSString *)callbackAcitvityStatushttpPostUrl {
    _callbackAcitvityStatushttpPostUrl = callbackAcitvityStatushttpPostUrl;
    [_parameter setObject:[NSString stringWithFormat:@"%@", callbackAcitvityStatushttpPostUrl] forKey:@"callbackAcitvityStatushttpPostUrl"];
}

#pragma mark - GCDAsyncSocketDelegate
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
    self.heartTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(checkLongConnectByServe) userInfo:nil repeats:YES];
    [self checkLongConnectByServe];

}

- (void)checkLongConnectByServe {
    NSString *longConnect;
    if (PLAYER_TestEnvironment) {
        longConnect = [NSString stringWithFormat:@"test.%@#%@#",PLAYER_AppID,_activityId];
    } else {
        longConnect = [NSString stringWithFormat:@"%@#%@#",PLAYER_AppID,_activityId];
    }
    NSData   *data  = [longConnect dataUsingEncoding:NSUTF8StringEncoding];
    [self.socket writeData:data withTimeout:-1 tag:1];
    
}

- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag {

}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    
    
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err {
    
    if (_isRecording) {
        
        _isRecording = NO;
        
        if (self.logPrintEnable) {
            NSLog(@"CNLiveStreamerKit-->由于监听心跳未能正常运作而暂时断开推流,reason:%@",err?err.localizedDescription:@"nil");
        }
        
        [_manager.kit.streamerBase stopStream];
        
        //如果socket异常断开,发送异常通知
        _streamErrorCode = CNLiveStreamErrorCode_ABNORMAL;
        _streamState = CNLiveStreamStateError;
        [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveStreamerStateDidChangeNotification
                                                            object:nil
                                                          userInfo:nil];
        
        [CNLiveStreamerTools getRealTimeString:^(NSString *timeString) {
            [self requestStopStreamerWithInfo:@"CNLiveStreamErrorCode_ABNORMAL_1" timeString:timeString];
        }];
        
        
        //重连失败通知开发者
        if (_retryFailed && _isCNLiveStreaming) {
            _reconnectStatus = CNLiveReconnectStatusFailed;
            [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveStreamerReconnectStatusChangedNotification
                                                                object:nil
                                                              userInfo:nil];
            [self recoverReconnectConfig];
        }
        
        if (_autoRetryCnt>0 && !_initiativeRetry) {
            [self tryReconnect];

        }
        
    }
    
    [self.heartTimer invalidate];
    self.heartTimer = nil;
}

#pragma mark - RM
- (void)initRCloudWithAppId:(NSString *)appId appKey:(NSString *)appKey connectResult:(void(^)(BOOL result))result {
    [[CNLiveMsgManager sharedCNLiveMsgManager] initCNLiveMsgToolsWithAppKey:appKey appId:appId];
    
    //连接RM服务器
    [[CNLiveMsgManager sharedCNLiveMsgManager] justOnLineSuccess:^(NSString *toolsId) {
        
        //加入聊天室
        [self joinRoomResult:result];
        
    } error:^(NSInteger errors) {
        
        if (result) {
            result(NO);
        }
        
    }];
    
}

//加入聊天室
- (void)joinRoomResult:(void(^)(BOOL result))result {
    //注册通知
    [self initRCloudNotificationObservers];
    
    NSString *contentId = _contentId;
    if (![_contentId containsString:@"_"]) {
        NSString *spId = [[PLAYER_AppID componentsSeparatedByString:@"_"] firstObject];
        contentId = [NSString stringWithFormat:@"%@_%@", spId, _contentId];
    }
    
    _roomId = [NSString stringWithFormat:@"CNLiveAnchorStatus_%@",contentId];
    
    //加入聊天室
    [[CNLiveMsgManager sharedCNLiveMsgManager] gatherIfNullCreate:_roomId messageCount:1 success:^(NSString *targetId) {
        if (result) {
            result(YES);
            
        }
        
    } error:^(NSInteger errors, NSString *targetId) {
        if (result) {
            result(NO);
            
        }
        
    }];
}

- (void)initRCloudNotificationObservers {
    //如果已经注册通知直接返回,无需重复注册
    if (_registerChatNoti) return;
    
    //接收消息通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveMessage:) name:CNLiveStreamerMsgReceiveNotification object:nil];
    
    _registerChatNoti = YES;
    
}

- (void)receiveMessage:(NSNotification *)noti {
    
    if (!noti.userInfo[@"message"]) return;
    
    int newValue = [noti.userInfo[@"message"] intValue];
    
    if (_originalStatus == newValue) return;    //如果新收到的状态与上一次状态一样不作处理
    
    if (!_originalStatus && newValue == 2) {
        return;
    }
    
    _originalStatus = newValue;
    
    if (newValue == 2) {
        //发送通知
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveServiceConnectBreakNotification object:nil  userInfo:nil];
        });
    }
    
}

- (void)quitRM {
    if (!_registerChatNoti) return;
    
    _registerChatNoti = NO;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CNLiveStreamerMsgReceiveNotification object:nil];
    
    if (![CNLiveStreamerTools isEmptyString:_roomId]) {
        [[CNLiveMsgManager sharedCNLiveMsgManager] disperse:_roomId success:^(NSString *targetId) {
            
        } error:^(NSInteger errors, NSString *targetId) {
            
        }];
    }
    
}

#pragma mark - getter
- (CNLiveWatermark *)watermark {
    if (!_watermark) {
        _watermark = [[CNLiveWatermark alloc] init];
    }
    return _watermark;
}

- (CNLiveStreamerBase *)streamerBase {
    if (!_streamerBase) {
        _streamerBase = [[CNLiveStreamerBase alloc] init];
    }
    return _streamerBase;
}

- (CNLiveAudioCapture *)audioCapture {
    if (!_audioCapture) {
        _audioCapture = [[CNLiveAudioCapture alloc] init];
    }
    return _audioCapture;
}

- (CNLiveBeautifyFaceFilter *)beautifyFaceFilter {
    if (!_beautifyFaceFilter) {
        _beautifyFaceFilter = [[CNLiveBeautifyFaceFilter alloc] init];
    }
    return _beautifyFaceFilter;
}

- (CNLiveBgmPlayer *)bgmPlayer {
    if (!_bgmPlayer) {
        _bgmPlayer = [[CNLiveBgmPlayer alloc] init];
    }
    return _bgmPlayer;
}

#pragma mark - dealloc
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [UIApplication sharedApplication].idleTimerDisabled = NO;
    
    [_manager destroyStreamerManager];
    _manager = nil;
}

- (UIView *)floatingWindowFrame:(CGRect)rect {
    KSYGPUView *gpuView = [[KSYGPUView alloc] init];
    gpuView.frame = CGRectMake(0, 0, rect.size.width, rect.size.height);
    [_manager.kit.vPreviewMixer addTarget:gpuView];
    UIView *view = [[UIView alloc] initWithFrame:rect];
    [view addSubview:gpuView];
    return view;
}

#pragma mark - data
- (void)requestCreateActivityParameter:(NSDictionary *)param success:(void(^)(void))successBlock failure :(void (^)(NSDictionary *errorDic))failureBlock {
    
    [CNLivePlayerNetworkManager POST:StreamerURL parameters:param success:^(NSURLResponse * _Nullable response, id  _Nullable responseObject) {
        
        if (![CNLiveStreamerTools isEmptyString:responseObject[@"errorCode"]] && [responseObject[@"errorCode"] intValue] == 0) {
            
            if (self.logPrintEnable) {
                NSLog(@"CNLiveGPUStreamerKit-->创建活动成功");
            }
            
            //创建活动成功后,连接RM,获取主播状态
            //            [self initRCloudWithAppId:SHARE_APPID appKey:SHARE_APPKEY connectResult:NULL];
            
            _activitySuccess = YES;
            
            NSString *url = responseObject[@"data"][@"location"];
            _hostURL = [NSURL URLWithString:url];
            
            [CNLiveStreamerTools getRealTimeString:^(NSString *timeString) {
                [self requestStartStreamer:successBlock failure:failureBlock timeString:timeString];
            }];
            
        } else {
            
            if (self.logPrintEnable) {
                NSLog(@"CNLiveGPUStreamerKit-->创建活动失败,失败原因:%@", responseObject);
            }
            
            failureBlock ? failureBlock(responseObject) : nil;
            
            //用于探针
            
            NSError *error = [CNLiveStreamerTools customErrorWithResponseObject:responseObject errorInfo:@"开启推流失败,请重试"];
            
            [CNLiveStreamerTools errorStat:error.userInfo.description activityId:_activityId];
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSDictionary *errorDic = @{@"errorCode": [NSString stringWithFormat:@"%ld", error.code],
                                   @"errorMessage": error.localizedDescription};
        
        failureBlock ? failureBlock(errorDic) : nil;
        
        if (self.logPrintEnable) {
            NSLog(@"CNLiveGPUStreamerKit-->创建活动失败,失败原因:%@", errorDic);
        }
        
        [CNLiveStreamerTools errorStat:error.userInfo.description activityId:_activityId];
        
    }];
    
}

//启动直播活动
- (void)requestStartStreamer:(void (^)(void))successBlock failure:(void (^)(NSDictionary *))failureBlock  timeString:(NSString *)timeString {
    _reteying = NO;
    
    NSMutableDictionary *parameter = [@{@"appId": PLAYER_AppID,
                                        @"activityId": _activityId,
                                        @"timestamp":timeString,
                                        @"platform_id":[NSBundle mainBundle].bundleIdentifier} copy] ;
    
    NSMutableDictionary *para = [CNLiveStreamerTools encryptionSignWithParameter:parameter];
    
    [CNLivePlayerNetworkManager GET:StartStreamerURL parameters:para success:^(NSURLResponse * _Nullable response, id  _Nullable responseObject) {
        
        if (responseObject[@"errorCode"] && [responseObject[@"errorCode"]isEqualToString:@"0"]) {   //开始活动success
            
            _isRecording = YES;
            BOOL linkResult;
            
            if (_socket.isDisconnected || !_socket) {
                self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
                NSError *error;
                linkResult = [self.socket connectToHost:Host onPort:Port withTimeout:5 error:&error];
            } else {
                linkResult = YES;
            }
            
            if (linkResult) {   //连接聊天室success
                
                if (_manager.kit.streamerBase.isStreaming) {
                    _streamState = CNLiveStreamStateConnected;
                    [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveStreamerStateDidChangeNotification
                                                                        object:nil
                                                                      userInfo:nil];
                }
                
                if (!_manager.kit.streamerBase.isStreaming) {
                    [_manager.kit.streamerBase startStream:_hostURL];
                }
                
                
                if (successBlock) {
                    successBlock();
                }
                
                if (self.logPrintEnable) {
                    //                    D_NSLog(@"CNLiveGPUStreamerKit-->开启活动成功 -----连接状态%@", share.kit.streamerBase.isStreaming ? @"YES" : @"NO");
                    NSLog(@"CNLiveGPUStreamerKit-->开启活动成功");
                }
                
                _initiativeRetry = NO;
                
                
            } else {            //连接聊天室fail
                
                _isRecording = NO;
                
                /**
                 *  开始活动成功但是聊天室连接失败应将活动状态置为“-2”
                 */
                [CNLiveStreamerTools getRealTimeString:^(NSString *timeString) {
                    [self requestStopStreamerWithInfo:@"CNLiveStreamErrorCode_JoinRoomFailed" timeString:timeString];
                }];
                
                /**
                 *  若返回前台,流没断,但是连接聊天室失败,需将流断开
                 */
                if (_manager.kit.streamerBase.isStreaming) {
                    [_manager.kit.streamerBase stopStream];
                }
                
                //用于错误探针
                NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"socket连接失败"}];
                
                [CNLiveStreamerTools errorStat:error.userInfo.description activityId:_activityId];
                
                //用于回调
                NSDictionary *errorDic = @{@"errorCode": @"-1",
                                           @"errorMessage": @"心跳连接失败,请重试"};
                
                if (self.logPrintEnable) {
                    NSLog(@"CNLiveGPUStreamerKit-->开启活动失败,失败原因:%@", errorDic);
                }
                
                //重连失败通知开发者
                if (_retryFailed && _isCNLiveStreaming) {
                    _reconnectStatus = CNLiveReconnectStatusFailed;
                    [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveStreamerReconnectStatusChangedNotification
                                                                        object:nil
                                                                      userInfo:nil];
                    [self recoverReconnectConfig];
                }
                
                //                NSLog(@"socketConnectFailed---->autoRetryCnt:%d----initiativeRetry:%@----reteying:%@----retryFailed:%@", _autoRetryCnt, _initiativeRetry ? @"YES" : @"NO", _reteying?@"YES":@"NO", _retryFailed?@"YES":@"NO");
                
                if (_autoRetryCnt>0 && !_initiativeRetry) {
                    [self tryReconnect];
                    //                    D_NSLog(@"CNLiveGPUStreamerKit-->reconnect ----- socket连接失败");
                    
                }
                
                failureBlock ? failureBlock(errorDic) : nil;
                
            }
            
        } else {   //开始活动失败
            
            _isRecording = NO;
            
            if (_manager.kit.streamerBase.isStreaming) {
                [_manager.kit.streamerBase stopStream];
            }
            
            //用于探针
            NSError *error = [CNLiveStreamerTools customErrorWithResponseObject:responseObject errorInfo:@"开启推流失败,请重试"];
            
            [CNLiveStreamerTools errorStat:error.userInfo.description activityId:_activityId];
            
            if (self.logPrintEnable) {
                NSLog(@"CNLiveGPUStreamerKit-->开启活动失败,失败原因:%@", responseObject);
            }
            
            //重连失败通知开发者
            if (_retryFailed && _isCNLiveStreaming) {
                _reconnectStatus = CNLiveReconnectStatusFailed;
                [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveStreamerReconnectStatusChangedNotification
                                                                    object:nil
                                                                  userInfo:nil];
                [self recoverReconnectConfig];
            }
            
            //            NSLog(@"startFailed---->autoRetryCnt:%d----initiativeRetry:%@----reteying:%@----retryFailed:%@", _autoRetryCnt, _initiativeRetry ? @"YES" : @"NO", _reteying?@"YES":@"NO", _retryFailed?@"YES":@"NO");
            
            if (_autoRetryCnt>0 && !_initiativeRetry) {
                [self tryReconnect];
                //                D_NSLog(@"CNLiveGPUStreamerKit-->reconnect ----- 启动活动失败");
            }
            
            failureBlock ? failureBlock(responseObject) : nil;
            
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        _isRecording = NO;
        
        if (_manager.kit.streamerBase.isStreaming) {
            [_manager.kit.streamerBase stopStream];
        }
        
        NSDictionary *errorDic = @{@"errorCode": [NSString stringWithFormat:@"%ld",error.code], @"errorMessage": error.localizedDescription};
        
        [CNLiveStreamerTools errorStat:error.userInfo.description activityId:_activityId];
        
        
        if (self.logPrintEnable) {
            NSLog(@"CNLiveGPUStreamerKit-->开启活动失败,失败原因:%@", errorDic);
        }
        
        //重连失败通知开发者
        if (_retryFailed && _isCNLiveStreaming) {
            _reconnectStatus = CNLiveReconnectStatusFailed;
            [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveStreamerReconnectStatusChangedNotification
                                                                object:nil
                                                              userInfo:nil];
            [self recoverReconnectConfig];
        }
        
        //        NSLog(@"no wlan---->autoRetryCnt:%d----initiativeRetry:%@----reteying:%@----retryFailed:%@", _autoRetryCnt, _initiativeRetry ? @"YES" : @"NO", _reteying?@"YES":@"NO", _retryFailed?@"YES":@"NO");
        
        if (_autoRetryCnt>0 && !_initiativeRetry) {
            [self tryReconnect];
            //            D_NSLog(@"CNLiveGPUStreamerKit-->reconnect ----- 启动活动(((请求)))失败");
        }
        
        failureBlock ? failureBlock(errorDic) : nil;
        
    }];
}

//结束直播活动
- (void)requestStopStreamerWithInfo:(NSString *)remark timeString:(NSString *)timeString {
    //    NSDate *date = [NSDate date];
    //    NSInteger time = [date timeIntervalSince1970];
    //    NSString *timeString = [NSString stringWithFormat:@"%ld", (long)time];
    
    NSMutableDictionary *parameter = [@{@"appId": PLAYER_AppID,
                                        @"activityId": _activityId,
                                        @"platform_id":[NSBundle mainBundle].bundleIdentifier,
                                        @"timestamp":timeString} mutableCopy];
    if (remark.length > 0) {
        [parameter setObject:remark forKey:@"remark"];
    }
    
    NSMutableDictionary *para = [CNLiveStreamerTools encryptionSignWithParameter:parameter];
    
    [CNLivePlayerNetworkManager GET:StopStreamerURL parameters:para success:^(NSURLResponse * _Nullable response, id  _Nullable responseObject) {
        
        if ([[NSString stringWithFormat:@"%@", responseObject[@"errorCode"]] isEqualToString:@"0"]) {
            
            if (self.logPrintEnable) {
                if (remark.length > 0) {
                    NSLog(@"CNLiveGPUStreamerKit-->异常结束推流error:%@,并成功通知后台", remark);
                } else {
                    //结束推流成功通知
                    _streamState = CNLiveStopStreamSuccess;
                    [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveStreamerStateDidChangeNotification
                                                                        object:nil
                                                                      userInfo:nil];
                    
                    NSLog(@"CNLiveGPUStreamerKit-->正常结束推流并成功通知后台");
                }
            }
            
            
            if ([CNLiveStreamerTools isEmptyString:remark]) {
                NSString *duration = responseObject[@"data"][@"duration"];
                if ([duration isKindOfClass:[NSString class]] && duration.length > 0) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveStreamerGetDurationNotification object:duration ? duration : @"0"];
                } else {
                    [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveStreamerGetDurationNotification object:@"0"];
                }
            }
            
            
        } else {
            
            if ([CNLiveStreamerTools isEmptyString:remark]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveStreamerGetDurationNotification object:@"0"];
                
            }
            
            if (self.logPrintEnable) {
                if (remark.length > 0) {
                    NSLog(@"CNLiveGPUStreamerKit-->异常结束推流error:%@,未能通知后台  %@", remark,responseObject);
                } else {
                    NSLog(@"CNLiveGPUStreamerKit-->正常结束推流,未能通知后台 %@",responseObject);
                    //结束推流失败通知
                    _streamState = CNLiveStopStreamFailure;
                    [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveStreamerStateDidChangeNotification
                                                                        object:nil
                                                                      userInfo:nil];
                }
            }
            
            
            NSError *error = [CNLiveStreamerTools customErrorWithResponseObject:responseObject errorInfo:@"结束推流失败"];
            
            [CNLiveStreamerTools errorStat:error.userInfo.description activityId:_activityId];
            
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (self.logPrintEnable) {
            if (remark.length > 0) {
                NSLog(@"CNLiveGPUStreamerKit-->异常结束推流error:%@,未能通知后台", remark);
            } else {
                NSLog(@"CNLiveGPUStreamerKit-->正常结束推流,未能通知后台");
            }
        }
        
        //结束推流失败通知
        _streamState = CNLiveStopStreamFailure;
        [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveStreamerStateDidChangeNotification
                                                            object:nil
                                                          userInfo:nil];
        
        [CNLiveStreamerTools errorStat:error.userInfo.description activityId:_activityId];
        
    }];
}

//创建直播活动
- (void)createActivityWithSuccess:(void (^)(void))successBlock failure:(void (^)(NSDictionary *))failureBlock  timeString:(NSString *)timeString {
    //如果不是纯音频推流,先判断是否已开启采集状态,若未开启直接返回
    if (!_pureAudioMode) {
        if (_manager.kit.captureState != KSYCaptureStateCapturing) {
            
            NSDictionary *errorDic = @{@"errorCode": @"-101",
                                       @"errorMessage": @"未开启采集状态"};
            
            failureBlock ? failureBlock(errorDic) : nil;
            return;
        }
    }
    
    NSDate *date = [NSDate date];
//    NSInteger time = [date timeIntervalSince1970];
//    NSString *timeString = [NSString stringWithFormat:@"%ld", (long)time];
    
    NSDictionary *params=@{@"platform_id":[NSBundle mainBundle].bundleIdentifier,
                           @"timestamp": timeString,
                           @"appId": PLAYER_AppID,
                           @"isHorizontalScreen":[NSString stringWithFormat:@"%d",_isHorizontalScreen],
                           @"uuid":[CNLiveStreamerTools getUidForStat:date]};
    
    [_parameter addEntriesFromDictionary:params];
    
    //避免创建活动失败,再次创建时字典中包含已加密sign
    [_parameter removeObjectForKey:@"sign"];
    
    //加密参数
    NSMutableDictionary *para = [CNLiveStreamerTools encryptionSignWithParameter:_parameter];
    
    [self requestCreateActivityParameter:para success:successBlock failure:failureBlock];
    
    [CNLiveStreamerTools statSDKWithDate:date activityId:_activityId];
    
}


@end