webRtcPlayerViewController.m 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531
  1. //
  2. // webRtcPlayerViewController.m
  3. // 双子星云手机
  4. //
  5. // Created by xd h on 2024/9/2.
  6. //
  7. #import "webRtcPlayerViewController.h"
  8. #import "webRtcPlayerViewController+AdjustBtnFrame.h"
  9. #import "webRtcPlayerViewController+AdjustPlayerViewFrame.h"
  10. #import "webRtcPlayerViewController+AppDelegate.h"
  11. #import "playerSetView.h"
  12. @interface webRtcPlayerViewController ()<MediaStreamClientEventsDelegate>
  13. {
  14. BOOL outputVolumeKVO;/*标记声音监听通知*/
  15. double lastTimestamp;/*最后一帧时间戳*/
  16. NSNumber *lastBytesReceived;/*最后一帧数据量*/
  17. //记录上次 线性增长接收包数
  18. long lasPacketsReceived;
  19. //记录上次 总丢包数据
  20. long lastAlllostData;
  21. //记录上次 丢包率
  22. double prelostRate;
  23. double prelostTimestamp;//计算丢包率时间戳(X秒算一次)
  24. BOOL isExitType;//退出云机
  25. NSInteger checkLinkTimerNumber;//0 --2 开始发起重连
  26. NSInteger preDelayedMS;//记录上一次延时数据 控制controlBtn 的图片刷新 非必要 不刷新
  27. NSInteger tryRelinkNum;//重连次数
  28. }
  29. @property (nonatomic, copy) NSTimer *playerSecondTimer; // 定时器-控制按钮
  30. @property (nonatomic, assign) RTCIceConnectionState linkState;
  31. @property (nonatomic, assign) BOOL didHandleRotation;//第一次处理旋转
  32. @property (nonatomic, assign) BOOL didReportWebRtcOKType;//上报打洞是否成功
  33. @property (nonatomic, assign) BOOL didReportWebRtcFailType;//上报打洞是否成功
  34. @property (nonatomic, strong)playerSetView *playerSetV;//推流设置页
  35. @property (nonatomic, strong)UILabel *testLostLabel;//测试验证丢包率的
  36. @end
  37. @implementation webRtcPlayerViewController
  38. @synthesize controlBtn;
  39. @synthesize isLan;
  40. - (void)viewDidLoad {
  41. [super viewDidLoad];
  42. // Do any additional setup after loading the view.
  43. [self.toolBar setHidden:YES];
  44. [self.navigationBar setHidden:YES];
  45. [self.navBarBGView setHidden:YES];
  46. [self.view setBackgroundColor:[UIColor blackColor]];
  47. _webRtcPlayerSessionId = [iTools getNowTimeStampString];
  48. if([DFPlayer sharedPlayer].state == DFPlayerStateBuffering
  49. ||[DFPlayer sharedPlayer].state == DFPlayerStatePlaying){
  50. _isCodeSuspendAudioType = YES;
  51. [[DFPlayer sharedPlayer] df_pause];
  52. }
  53. prelostRate = 0.0;
  54. }
  55. - (void)viewWillAppear:(BOOL)animated {
  56. [super viewWillAppear:animated];
  57. // 屏幕常亮
  58. [UIApplication sharedApplication].idleTimerDisabled = YES;
  59. [[UIApplication sharedApplication] setStatusBarHidden:YES];
  60. }
  61. - (void)viewDidAppear:(BOOL)animated
  62. {
  63. [super viewDidAppear:animated];
  64. [self noEnablePanRightBack];
  65. [self addKVOObserverFun];
  66. //ksharedAppDelegate.supportScreenRotateType = YES;
  67. }
  68. - (void)viewDidDisappear:(BOOL)animated{
  69. [super viewDidDisappear:animated];
  70. [self HandleSomethingByExitVC];
  71. }
  72. //- (BOOL)shouldAutorotate {
  73. // // 根据你的需求来决定是否允许自动旋转
  74. // // 这里我们默认不允许,除非有特定的逻辑允许
  75. // return NO; // 或者根据某个条件返回YES
  76. //}
  77. #pragma mark 退出事件处理
  78. -(void)HandleSomethingByExitVC
  79. {
  80. [UIApplication sharedApplication].idleTimerDisabled = NO;
  81. [[UIApplication sharedApplication] setStatusBarHidden:NO];
  82. isExitType = YES;
  83. if(_mediaStream){
  84. [_mediaStream disconnect];
  85. _mediaStream = nil;
  86. }
  87. [self enablePanRightBack];
  88. [self removeKVOObserverFun];
  89. ksharedAppDelegate.supportScreenRotateType = NO;
  90. ksharedAppDelegate.isPlayerScreenLandscapeType = NO;
  91. [self removeNewIndicator];
  92. if(_playerSecondTimer){
  93. [_playerSecondTimer invalidate];
  94. _playerSecondTimer = nil;
  95. }
  96. _webRtcMsgMod = nil;
  97. if(_playerSetV){
  98. [_playerSetV removeFromSuperview];
  99. _playerSetV = nil;
  100. }
  101. }
  102. - (void)setWebRtcMsgMod:(webRtcMsgModel *)webRtcMsgMod
  103. {
  104. _webRtcMsgMod = webRtcMsgMod;
  105. [self beginWebRtcPlayFun];
  106. }
  107. #pragma mark 开始拉流
  108. - (void)beginWebRtcPlayFun
  109. {
  110. if(_mediaStream){
  111. //[_mediaStream disconnect];
  112. //[_mediaStream removeFromSuperview];
  113. //_mediaStream = nil;
  114. }
  115. //2.客户端开始写日志
  116. [ksharedAppDelegate.WebRtcLogger start];
  117. _mediaStream = [[RTC_OBJC_TYPE(AMediaStream) alloc] initWithFrame:CGRectZero];
  118. [_mediaStream setEventDelegate:self];
  119. [self.view addSubview:_mediaStream];
  120. HLog(@"_mediaStream:%@",_mediaStream)
  121. [_mediaStream mas_makeConstraints:^(MASConstraintMaker *make) {
  122. make.left.mas_equalTo(0.f);
  123. make.bottom.mas_equalTo(0.f);
  124. make.right.mas_equalTo(0.f);
  125. make.top.mas_equalTo(0.f);
  126. }];
  127. //判断是否是全屏
  128. BOOL fullscreenType = [HWDataManager getBoolWithKey:Consn_player_full_screen_show];
  129. NSInteger curResolution = [HWDataManager getIntegerWithKey:Const_cloudPhone_cur_resolution];
  130. CGFloat curWidth = 720.0;
  131. CGFloat curHeight = 1280.0;
  132. if(curResolution == 0 || curResolution == 1){
  133. curWidth = 720.0;
  134. curHeight = 1280.0;
  135. }
  136. else{
  137. curWidth = 1080.0;
  138. curHeight = 1920.0;
  139. }
  140. CGSize phoneSize = CGSizeMake(curWidth, curHeight);
  141. //云机分辨率被改成 720.0, 1280.0
  142. // if(ksharedAppDelegate.couldPhone_W_PHONE == 720 && ksharedAppDelegate.couldPhone_H_PHONE == 1280) {//云机可能存在的分辨率
  143. // phoneSize = CGSizeMake(720.0, 1280.0);
  144. // }
  145. if(fullscreenType){
  146. phoneSize = [RCCommandHelp commondToSetFullScreenPhoneSizeBySize];
  147. }
  148. [self linkWebRtcFunWithSize:phoneSize];
  149. [self initBaseUIFun];
  150. [self setTimerCountDown];
  151. [self showNewIndicatorWithCanBack:YES canTouch:NO];
  152. }
  153. #pragma mark 链接webrtc
  154. - (void)linkWebRtcFunWithSize:(CGSize)phoneSize
  155. {
  156. webrtcServerModel * webrtcServerMod = ksharedAppDelegate.bestWebrtcServerModel;
  157. //链接用
  158. NSString *signallingUrl = [[NSString alloc] initWithFormat:@"%@:%@",webrtcServerMod.signallingIp,webrtcServerMod.signallingPort];
  159. NSURL *url = [NSURL URLWithString:signallingUrl];
  160. //ice用
  161. NSString *iceUrl = [[NSString alloc] initWithFormat:@"%@:%@",webrtcServerMod.turnIp,webrtcServerMod.turnPort];
  162. NSMutableDictionary *ice = [NSMutableDictionary new];
  163. if(iceUrl){
  164. [ice setValue:iceUrl forKey:@"CHINANET"];
  165. [ice setValue:iceUrl forKey:@"CMNET"];
  166. [ice setValue:iceUrl forKey:@"UNICOM"];
  167. }
  168. NSString *roomName = _webRtcMsgMod.data.uniqueIdentifier;
  169. NSInteger cardDensity = 320;//480;
  170. //判断是否是全屏
  171. BOOL fullscreenType = [HWDataManager getBoolWithKey:Consn_player_full_screen_show];
  172. if(fullscreenType){
  173. //cardDensity = 380;
  174. //cardDensity = 320;
  175. //cardDensity = 480;
  176. }
  177. //码率根据网络设置 wifi 8M 移动网络 4M ->改为 4M 2M
  178. NSInteger bitrate = 4*1024;
  179. if([AFNetworkReachabilityManager sharedManager].isReachableViaWWAN){
  180. bitrate = 2*1024;
  181. }
  182. //1.盒子开始写20秒日志
  183. //start 拉流前调用设置本次拉流记录推流端日志到指定文件与记录时间 秒 单位。
  184. //filePathName = /sdcard/webrtc_box.log captureTime = 30s
  185. [_mediaStream setCardLogToFile:@"/sdcard/webrtc_box.log" captureTime:@"20"];
  186. NSString *logstr = [[NSString alloc] initWithFormat:@"webRtcPlayer start link--%@",signallingUrl];
  187. [cachesFileManager writeLogsWithMsg:logstr];
  188. //2.客户端开始写日志
  189. [ksharedAppDelegate.WebRtcLogger start];
  190. NSString* curToken = @"vclusters";
  191. BOOL isImageFor144Orlater = [HWDataManager getBoolWithKey:stringKeyAddSn(Const_image_version_for_new_token)];
  192. if(isImageFor144Orlater || ksharedAppDelegate.isImageFor144Orlater)
  193. {
  194. curToken = @"mediakit";
  195. }
  196. NSInteger result = [_mediaStream start:url
  197. ice:ice
  198. sn:roomName
  199. direct:0
  200. fmt:1//1(h264) 5(h265)
  201. videoWidth:(NSInteger)phoneSize.width
  202. videoHeight:(NSInteger)phoneSize.height
  203. fps:30
  204. bitrate:bitrate//3200//3000
  205. cardWidth:(NSInteger)phoneSize.width//0//1080//0
  206. cardHeight:(NSInteger)phoneSize.height//0//1920//0
  207. cardDensity:cardDensity
  208. token:curToken];
  209. HLog(@"result:%ld",result)
  210. [_mediaStream setShouldGetStats:YES];
  211. //清晰度码率最大上限 流畅1800 标清2200 高清2800 跟上面的 bitrate是同一个意思
  212. //[_mediaStream setMaxBitrate:@2800];
  213. }
  214. #pragma mark 重连
  215. - (void)relinkWebRtcFun
  216. {
  217. // if(_linkState == RTCIceConnectionStateConnected
  218. // || _linkState == RTCIceConnectionStateCompleted)
  219. // {//链接中 不处理重连事件
  220. // HLog(@"链接中 不处理重连事件")
  221. // return;
  222. // }
  223. if(isExitType){
  224. return;
  225. }
  226. HLog(@"发起重连 ......")
  227. [cachesFileManager writeLogsWithMsg:@"webRtcPlayer relinkWebRtcFun"];
  228. KWeakSelf
  229. mainBlock(^{
  230. [weakSelf showNewIndicatorWithCanBack:YES canTouch:NO];
  231. NSInteger curResolution = [HWDataManager getIntegerWithKey:Const_cloudPhone_cur_resolution];
  232. CGFloat curWidth = 720.0;
  233. CGFloat curHeight = 1280.0;
  234. if(curResolution == 0 || curResolution == 1){
  235. curWidth = 720.0;
  236. curHeight = 1280.0;
  237. }
  238. else{
  239. curWidth = 1080.0;
  240. curHeight = 1920.0;
  241. }
  242. //判断是否是全屏
  243. BOOL fullscreenType = [HWDataManager getBoolWithKey:Consn_player_full_screen_show];
  244. CGSize phoneSize = CGSizeMake(curWidth, curHeight);
  245. if(fullscreenType){
  246. phoneSize = [RCCommandHelp commondToSetFullScreenPhoneSizeBySize];
  247. }
  248. //客户端停止写日志
  249. [ksharedAppDelegate.WebRtcLogger stop];
  250. [weakSelf linkWebRtcFunWithSize:phoneSize];
  251. });
  252. }
  253. #pragma mark 重连
  254. - (void)relinkWebRtcFunByBecomeActive{
  255. [self.mediaStream disconnect];// 断开会自动重连 防止多路流的清理
  256. }
  257. #pragma mark 初始化其他UI
  258. - (void)initBaseUIFun
  259. {
  260. if(_bottomContrView){
  261. [_bottomContrView removeFromSuperview];
  262. _bottomContrView = nil;
  263. }
  264. _bottomContrView = [[webRtcPlayerBottomContrView alloc] init];
  265. [self.view addSubview:_bottomContrView];
  266. [self getPlayerBottomNavShowOrHidefun];
  267. KWeakSelf
  268. _bottomContrView.didClickButtonFun = ^(NSInteger tag) {
  269. [weakSelf didClickBottomFunBy:tag];
  270. };
  271. /*控制按钮*/
  272. if(controlBtn){
  273. [controlBtn removeFromSuperview];
  274. controlBtn = nil;
  275. }
  276. UIImage *driftBtnImage = [UIImage imageNamed:@"you_icon"];
  277. controlBtn = [[UIButton alloc] init];
  278. [controlBtn setBackgroundColor:[UIColor clearColor]];
  279. [controlBtn setBackgroundImage:driftBtnImage forState:(UIControlStateNormal)];
  280. [controlBtn addTarget:self
  281. action:@selector(controlBtnPressed:)
  282. forControlEvents:(UIControlEventTouchUpInside)];
  283. [self.view addSubview:controlBtn];
  284. //拖拽事件等
  285. UIPanGestureRecognizer *gester = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(controlBtnPanGestureCallback:)];
  286. [controlBtn addGestureRecognizer:gester];
  287. //gester.delegate = self;
  288. [self initPointForControlBtnFun];
  289. _testLostLabel = [[UILabel alloc] init];
  290. _testLostLabel.textColor = [UIColor greenColor];
  291. //_testLostLabel.textAlignment = NSTextAlignmentCenter;
  292. _testLostLabel.font = [UIFont systemFontOfSize:14.0];
  293. _testLostLabel.numberOfLines = 0;
  294. [self.view addSubview:_testLostLabel];
  295. [_testLostLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  296. make.left.mas_equalTo(20);
  297. make.right.mas_equalTo(-20);
  298. make.top.mas_equalTo(100.f);
  299. }];
  300. }
  301. #pragma mark 设置 controlBtn 的初始位置
  302. - (void)initPointForControlBtnFun
  303. {
  304. CGFloat h_w_controlBtn = 60.f;
  305. /*区分横竖屏*/
  306. if (_mediaStream.hw_w > _mediaStream.hw_h){
  307. [controlBtn setFrame:CGRectMake((_mediaStream.hw_w - h_w_controlBtn)/2.f, _mediaStream.hw_h - h_w_controlBtn - 20.f, h_w_controlBtn, h_w_controlBtn)];
  308. }else{
  309. //默认居右
  310. //[mPlayerView.controlBtn setFrame:CGRectMake(mPlayerView.width - h_w_controlBtn - 20.f, (SCREEN_H - h_w_controlBtn)/2.f, h_w_controlBtn, h_w_controlBtn)];
  311. //默认居左
  312. [controlBtn setFrame:CGRectMake( h_w_controlBtn + 10.f, (SCREEN_H - h_w_controlBtn)/2.f, h_w_controlBtn, h_w_controlBtn)];
  313. }
  314. }
  315. #pragma mark 定时器
  316. - (void)setTimerCountDown {
  317. HLog(@"开启一个");
  318. if (_playerSecondTimer) {
  319. // 取消定时器
  320. [_playerSecondTimer invalidate];
  321. _playerSecondTimer = nil;
  322. }
  323. // 初始化值计时数据
  324. //self.adjustTime = 1;
  325. //self.concentTime = [iTools getNowTimeStamp];
  326. _playerSecondTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(timerChange) userInfo:nil repeats:YES];
  327. [[NSRunLoop currentRunLoop] addTimer:_playerSecondTimer forMode:NSRunLoopCommonModes];
  328. }
  329. #pragma mark 定时器响应事件
  330. - (void)timerChange {
  331. [self extensionAdjustBtnFrameCheckAdjustTime];// 1、悬浮球3s后 自动靠边隐藏
  332. //[self checkConcentTime];// 3、30s之后 没有收到拉流数据 自动断开链接
  333. checkLinkTimerNumber ++;
  334. if(checkLinkTimerNumber == 3){
  335. checkLinkTimerNumber = 0;
  336. if(_linkState != RTCIceConnectionStateConnected
  337. && _linkState != RTCIceConnectionStateCompleted){
  338. if(!_didReportWebRtcFailType){//还没上报过通道链接情况
  339. tryRelinkNum ++;
  340. if(tryRelinkNum == 2){
  341. tryRelinkNum = 0;
  342. _didReportWebRtcFailType = YES;
  343. [[webRtcManager shareManager] reportWebRtcRePoportTypeIsChannel:YES withStats:nil withSessionId:_webRtcPlayerSessionId];
  344. //[self showLinkPhoneErrorFun];
  345. //检测盒子心跳
  346. [self checkBoxHeartbeatFun];
  347. }
  348. }
  349. [self relinkWebRtcFun];
  350. }
  351. }
  352. }
  353. #pragma mark 云机连接不上
  354. - (void)showLinkPhoneErrorFun
  355. {
  356. [[addLogObject shareInstance] gotoAddLogFun];
  357. KWeakSelf
  358. [[errorAlertTool shareInstance] showNetErrorAlertFun:5 didClickBut:^(NSInteger tag) {
  359. if(tag == 1){
  360. [weakSelf relinkWebRtcFun];
  361. }
  362. else if(tag == 5){
  363. [weakSelf exitCloudPhoneFun];
  364. }
  365. }];
  366. }
  367. #pragma mark 控制按钮点击事件
  368. - (void)controlBtnPressed:(UIButton*)but
  369. {
  370. if(_playerSetV){
  371. [ksharedAppDelegate.window addSubview:_playerSetV];
  372. [_playerSetV mas_remakeConstraints:^(MASConstraintMaker *make) {
  373. make.left.mas_equalTo(0);
  374. make.right.mas_equalTo(0);
  375. make.top.mas_equalTo(0.f);
  376. make.bottom.mas_equalTo(0.f);
  377. }];
  378. [_playerSetV setAllSwitchFun];
  379. return;
  380. }
  381. _playerSetV = [[playerSetView alloc] init];
  382. [ksharedAppDelegate.window addSubview:_playerSetV];
  383. [_playerSetV mas_makeConstraints:^(MASConstraintMaker *make) {
  384. make.left.mas_equalTo(0);
  385. make.right.mas_equalTo(0);
  386. make.top.mas_equalTo(0.f);
  387. make.bottom.mas_equalTo(0.f);
  388. }];
  389. KWeakSelf
  390. _playerSetV.didClickButtonFun = ^(NSInteger tag) {
  391. switch (tag) {
  392. case 1:
  393. {//设置分辨率 720
  394. [weakSelf didClickSetResolution720Fun];
  395. }
  396. break;
  397. case 2:
  398. {//设置分辨率 1080
  399. [weakSelf didClickSetResolution1080Fun];
  400. }
  401. break;
  402. case 200:
  403. {//截图
  404. [weakSelf didClickshortCatFun];
  405. }
  406. break;
  407. #pragma mark 重启盒子
  408. case 202:
  409. {
  410. [weakSelf didClickRestartFun];
  411. }
  412. break;
  413. case 100:
  414. {//退出云机
  415. [weakSelf exitCloudPhoneFun];
  416. }
  417. break;
  418. case 201:
  419. {
  420. BOOL fullscreenType = [HWDataManager getBoolWithKey:Consn_player_full_screen_show];
  421. if(fullscreenType){
  422. [weakSelf showOpenTVP2PFun];
  423. }
  424. else{
  425. [weakSelf openTvShowFun];
  426. }
  427. }
  428. break;
  429. case 301:
  430. {
  431. weakSelf.controlBtn.userInteractionEnabled = NO;
  432. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  433. weakSelf.controlBtn.userInteractionEnabled = YES;
  434. });
  435. [weakSelf showCloseTVP2PFun];
  436. }
  437. break;
  438. default:
  439. break;
  440. }
  441. };
  442. }
  443. #pragma mark 设置分辨率 720*1280
  444. - (void)didClickSetResolution720Fun
  445. {
  446. CGFloat tempRate = 0.0;
  447. NSInteger cardDensity = 320;//480;
  448. CGSize size = CGSizeMake(720.0, 1280.0);
  449. if(isLan){
  450. size = CGSizeMake(1280.0, 720.0);
  451. }
  452. [self setCardSize:(NSInteger)size.width cardHeight:(NSInteger)size.height cardDensity:cardDensity];
  453. tempRate = size.width/size.height;
  454. if (tempRate > 1) {/*横屏*/
  455. [self setLanMas_makeWithImageRate:tempRate];
  456. }else{/*竖屏*/
  457. [self setPoMas_makeWithImageRate:tempRate];
  458. }
  459. }
  460. #pragma mark 设置分辨率 1080*1920
  461. - (void)didClickSetResolution1080Fun
  462. {
  463. CGFloat tempRate = 0.0;
  464. NSInteger cardDensity = 320;//480;
  465. CGSize size = CGSizeMake(1080.0, 1920.0);
  466. if(isLan){
  467. size = CGSizeMake(1920.0, 1080.0);
  468. }
  469. [self setCardSize:(NSInteger)size.width cardHeight:(NSInteger)size.height cardDensity:cardDensity];
  470. tempRate = size.width/size.height;
  471. if (tempRate > 1) {/*横屏*/
  472. [self setLanMas_makeWithImageRate:tempRate];
  473. }else{/*竖屏*/
  474. [self setPoMas_makeWithImageRate:tempRate];
  475. }
  476. }
  477. #pragma mark 点击了截图
  478. - (void)didClickshortCatFun
  479. {
  480. [[webRtcManager shareManager] screenshotInCloudPhoneFun];
  481. }
  482. #pragma mark 点击了重启云机
  483. - (void)didClickRestartFun
  484. {
  485. KWeakSelf
  486. /*弹窗提示重启*/
  487. ComontAlretViewController *nextVC = [[ComontAlretViewController alloc] initWithTiTle:NSLocalizedString(@"my_set_no_restart_phone_tips",nil)
  488. msg:@""
  489. imageStr:@""
  490. cancelTitle:NSLocalizedString(@"other_cancel",nil)
  491. okTitle:NSLocalizedString(@"my_set_no_restart_phone_btn_ok",nil) isOkBtnHighlight:NO
  492. didClickOk:^{
  493. [weakSelf needToRebootFun];
  494. //提示语
  495. [[iToast makeText:NSLocalizedString(@"player_link_rebooting_Tips",nil)] show];
  496. } didClickCancel:^{
  497. }];
  498. nextVC.modalPresentationStyle = UIModalPresentationCustom;
  499. [self presentViewController:nextVC animated:YES completion:^{
  500. nextVC.view.superview.backgroundColor = [UIColor clearColor];
  501. }];
  502. }
  503. #pragma mark p2p通道 重启云机
  504. - (void)needToRebootFun
  505. {
  506. [cachesFileManager writeLogsWithMsg:@"webRtcPlayer click Reboot"];
  507. [[webRtcManager shareManager] needToRebootFun];
  508. [self startForceStartTimerFun];
  509. [self pauseStream];
  510. [webRtcManager shareManager].isRebootIngType = YES;
  511. [self showNewIndicatorWithCanBack:YES canTouch:NO];
  512. }
  513. #pragma mark X 秒后检查是否软件重启成功
  514. - (void)startForceStartTimerFun
  515. {
  516. KWeakSelf
  517. //1. 5秒后跟硬件发起硬重启
  518. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  519. [weakSelf updateForceStartFun];
  520. });
  521. //2. 20秒后尝试重连
  522. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(20 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  523. [weakSelf relinkWebRtcFun];
  524. [[webRtcManager shareManager] relinkWebRtcFun];
  525. });
  526. }
  527. #pragma mark 需要强制重启
  528. - (void)updateForceStartFun{
  529. NSString* curSn = ksharedAppDelegate.DeviceThirdIdMod.data.changeSn;
  530. NSMutableDictionary *paraDict = [NSMutableDictionary dictionary];
  531. [paraDict setValue:curSn forKey:@"sn"];
  532. [paraDict setValue:[NSNumber numberWithBool:YES] forKey:@"isForceStart"];
  533. [[netWorkManager shareInstance] CommonPostCallBackCode:updateForceStart Parameters:paraDict success:^(id _Nonnull responseObject) {
  534. SuperModel *model = [[SuperModel alloc] initWithDictionary:responseObject error:nil];
  535. if (model.status == 0) {
  536. }
  537. else
  538. {
  539. }
  540. } failure:^(NSError * _Nonnull error) {
  541. HLog(@"%@", error);
  542. }];
  543. }
  544. #pragma mark 退出云机
  545. - (void)exitCloudPhoneFun
  546. {
  547. [cachesFileManager writeLogsWithMsg:@"webRtcPlayer click exitCloudPhone"];
  548. //[self setShowImgAndVoiceTypeFun:NO];
  549. if(isLan){//保证竖屏
  550. [self player_rotateToInterfaceOrientation:UIInterfaceOrientationPortrait];
  551. }
  552. [self.navigationController popViewControllerAnimated:YES];
  553. ksharedAppDelegate.supportScreenRotateType = NO;
  554. [self HandleSomethingByExitVC];
  555. if(_isCodeSuspendAudioType){
  556. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  557. [[DFPlayer sharedPlayer] df_play];
  558. });
  559. }
  560. }
  561. #pragma mark 显示关闭投屏提示语
  562. - (void)showOpenTVP2PFun{
  563. /*弹窗提示TV投屏*/
  564. ComontAlretViewController *nextVC = [[ComontAlretViewController alloc] initWithTiTle:NSLocalizedString(@"File_upload_Record_clear_Tip_title",nil)
  565. msg:NSLocalizedString(@"cloudPhone_fullscreen_tvshow_tip",nil)
  566. imageStr:@""
  567. cancelTitle:NSLocalizedString(@"other_cancel",nil)
  568. okTitle:NSLocalizedString(@"my_set_TVP2P_Open_sure",nil) isOkBtnHighlight:YES
  569. didClickOk:^{
  570. [self openTvShowFun];
  571. //关闭全屏屏
  572. [HWDataManager setBoolWithKey:Consn_player_full_screen_show value:NO];
  573. [self setPlayerFullScreenNotFun];
  574. [self->_playerSetV handleResolutionUIFun];
  575. } didClickCancel:^{
  576. }];
  577. nextVC.modalPresentationStyle = UIModalPresentationCustom;
  578. [self presentViewController:nextVC animated:YES completion:^{
  579. nextVC.view.superview.backgroundColor = [UIColor clearColor];
  580. }];
  581. }
  582. #pragma mark 开始投屏
  583. - (void)openTvShowFun
  584. {
  585. self.controlBtn.userInteractionEnabled = NO;
  586. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  587. self->controlBtn.userInteractionEnabled = YES;
  588. });
  589. [[webRtcManager shareManager] onTvFun];
  590. [[iToast makeText:NSLocalizedString(@"cloudPhone_TV_show_tip",nil)] show];
  591. //数据埋点
  592. [[netWorkManager shareInstance] DataEmbeddingPointBy:3 withEventValue:@"Cloud_tv"];
  593. }
  594. #pragma mark 显示关闭投屏提示语
  595. - (void)showCloseTVP2PFun{
  596. /*弹窗提示TV投屏*/
  597. ComontAlretViewController *nextVC = [[ComontAlretViewController alloc] initWithTiTle:NSLocalizedString(@"my_set_no_close_TV_p2p_tip",nil)
  598. msg:@""
  599. imageStr:@""
  600. cancelTitle:NSLocalizedString(@"other_cancel",nil)
  601. okTitle:NSLocalizedString(@"my_set_TVP2P_Open_sure",nil) isOkBtnHighlight:YES
  602. didClickOk:^{
  603. [self gotoCloseTVP2PFun];
  604. } didClickCancel:^{
  605. //HLog(@"2222");
  606. }];
  607. nextVC.modalPresentationStyle = UIModalPresentationCustom;
  608. [self presentViewController:nextVC animated:YES completion:^{
  609. nextVC.view.superview.backgroundColor = [UIColor clearColor];
  610. }];
  611. }
  612. #pragma mark 确认开始TV投屏
  613. -(void)gotoCloseTVP2PFun
  614. {
  615. [[webRtcManager shareManager] offTvFun];
  616. }
  617. #pragma mark 挤下线功能
  618. -(void)offlineOtherPhoneFun
  619. {
  620. NSString *curOaidStr = [RcGameWQKeyChain getOaidStringFun];
  621. if(!curOaidStr){
  622. curOaidStr = @"";
  623. }
  624. NSString *commondStr = [[NSString alloc] initWithFormat:@"{\"type\":\"login\",\"value\":\"%@\"}",curOaidStr];
  625. [self send_dataInPlayer:commondStr];
  626. }
  627. #pragma mark 单点登录被挤下线弹框
  628. - (void)LogoutByOtherFun:(NSString*)oaid
  629. {
  630. if(logoutAlertVC){
  631. return;
  632. }
  633. [cachesFileManager writeLogsWithMsg:@"webRtcPlayer LogoutByOtherFun"];
  634. NSString *curOaidStr = [RcGameWQKeyChain getOaidStringFun];
  635. if(oaid
  636. && oaid.length >0
  637. && [oaid isEqualToString:curOaidStr]){
  638. return;
  639. }
  640. //[self didReceiveLogoutMsgFun];
  641. //yyyy-MM-dd HH:mm:ss
  642. NSString*dateStr = [iTools getNowTimeString2];
  643. if(dateStr && dateStr.length == 19){
  644. dateStr = [dateStr substringWithRange:NSMakeRange(11, 5)];
  645. }
  646. NSString *LogoutTimerStr = [[NSString alloc] initWithFormat:@"%@%@%@",NSLocalizedString(@"single_sign_on_Tips_one",nil),dateStr,NSLocalizedString(@"single_sign_on_Tips_two",nil)];
  647. NSString * loginAgainStr = NSLocalizedString(@"single_sign_on_login_again",nil);
  648. BOOL isOkBtnHighlight = YES;
  649. if(!ksharedAppDelegate.DeviceThirdIdMod.data.isPrivacyMode){
  650. loginAgainStr = @"";
  651. isOkBtnHighlight = NO;
  652. }
  653. KWeakSelf
  654. if(ksharedAppDelegate.isDidShowPwdType){
  655. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  656. [weakSelf LogoutByOtherFun:oaid];
  657. HLog(@"weakSelf LogoutByOtherFun")
  658. });
  659. return;
  660. }
  661. //被挤下线 停止拉流
  662. [self pauseStream];
  663. if(isLan){//保证竖屏
  664. [self player_rotateToInterfaceOrientation:UIInterfaceOrientationPortrait];
  665. }
  666. //退出推流页
  667. [self.navigationController popViewControllerAnimated:NO];
  668. //与安卓保存一致 tabbar 退倒nas页
  669. // [ksharedAppDelegate.mainTabBar setSelectedIndex:0];
  670. [self HandleSomethingByExitVC];
  671. /*弹窗提示重启*/
  672. //KWeakSelf
  673. logoutAlertVC = [[ComontAlretViewController alloc] initWithTiTle:NSLocalizedString(@"single_sign_on_Tips_logout",nil)
  674. msg:LogoutTimerStr
  675. imageStr:@""
  676. cancelTitle:NSLocalizedString(@"single_sign_on_exit",nil)
  677. okTitle:loginAgainStr isOkBtnHighlight:isOkBtnHighlight
  678. didClickOk:^{
  679. self->logoutAlertVC = nil;
  680. [[NSNotificationCenter defaultCenter] postNotificationName:lockBypwdNotification object:nil];
  681. } didClickCancel:^{
  682. //exit(0);/*强制退出app*/
  683. }];
  684. logoutAlertVC.modalPresentationStyle = UIModalPresentationCustom;
  685. logoutAlertVC.view.backgroundColor = [UIColor blackColor];
  686. [[iTools appRootViewController] presentViewController:logoutAlertVC animated:YES completion:^{
  687. self->logoutAlertVC.view.superview.backgroundColor = [UIColor clearColor];
  688. }];
  689. }
  690. #pragma mark 底部按钮事件
  691. - (void)didClickBottomFunBy:(NSInteger)tag
  692. {
  693. int keyType = 0;
  694. if(tag == 1){//task
  695. keyType = 187;
  696. }
  697. else if(tag == 2){//home
  698. keyType = 3;
  699. }
  700. else if(tag == 3){//back
  701. keyType = 4;
  702. }
  703. if(keyType > 0){
  704. [self didClickKeyEventFunBy:keyType];
  705. }
  706. }
  707. #pragma mark 按键事件
  708. // home 3 back 4 task 187 volumeUp 24 volumeDown 25
  709. - (void)didClickKeyEventFunBy:(int)keyType
  710. {
  711. [_mediaStream sendKey:keyType];
  712. }
  713. #pragma mark 云机交互的消息发送 走P2P通道
  714. -(void)send_data:(NSString*)commandStr
  715. {
  716. [[webRtcManager shareManager] send_data:commandStr];
  717. }
  718. #pragma mark 云机交互的消息发送 走音视频推拉流通道
  719. -(void)send_dataInPlayer:(NSString*)commandStr
  720. {
  721. [_mediaStream sendData:commandStr];
  722. }
  723. #pragma mark -- /*底部导航栏开关通知*/
  724. - (void)getPlayerBottomNavShowOrHidefun
  725. {
  726. BOOL haveShowBottonNavType = ![HWDataManager getBoolWithKey:Consn_player_Nav_hide];
  727. if(haveShowBottonNavType){
  728. _bottomContrView.hidden = NO;
  729. }
  730. else{
  731. _bottomContrView.hidden = YES;
  732. }
  733. }
  734. #pragma mark -- /*全面屏开关通知*/
  735. - (void)setPlayerFullScreenNotFun
  736. {
  737. BOOL fullscreenType = [HWDataManager getBoolWithKey:Consn_player_full_screen_show];
  738. CGFloat tempRate = 0.0;
  739. NSInteger cardDensity = 320;//480;
  740. //重新设置分辨率
  741. if(fullscreenType){
  742. //cardDensity = 380;//480;//422;//380;//460;
  743. CGSize size = [RCCommandHelp commondToSetFullScreenPhoneSizeBySize];
  744. if(isLan){
  745. if(size.width < size.height){
  746. size = CGSizeMake(size.height,size.width);
  747. }
  748. }
  749. [self setCardSize:size.width cardHeight:size.height cardDensity:cardDensity];
  750. tempRate = (size.width *1.0)/(size.height *1.0);
  751. }
  752. else{
  753. NSInteger curResolution = [HWDataManager getIntegerWithKey:Const_cloudPhone_cur_resolution];
  754. CGFloat curWidth = 720.0;
  755. CGFloat curHeight = 1280.0;
  756. if(curResolution == 0 || curResolution == 1){
  757. curWidth = 720.0;
  758. curHeight = 1280.0;
  759. }
  760. else{
  761. curWidth = 1080.0;
  762. curHeight = 1920.0;
  763. }
  764. CGSize size = CGSizeMake(curWidth, curHeight);
  765. if(isLan){
  766. size = CGSizeMake(curHeight, curWidth);
  767. }
  768. [self setCardSize:(NSInteger)size.width cardHeight:(NSInteger)size.height cardDensity:cardDensity];
  769. tempRate = size.width/size.height;
  770. }
  771. //dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  772. if (tempRate > 1) {/*横屏*/
  773. [self setLanMas_makeWithImageRate:tempRate];
  774. }else{/*竖屏*/
  775. [self setPoMas_makeWithImageRate:tempRate];
  776. }
  777. // });
  778. }
  779. #pragma mark -- /*推流中修改卡的分辨率*/
  780. - (void)setCardSize:(NSInteger)cardWidth
  781. cardHeight:(NSInteger)cardHeight
  782. cardDensity:(NSInteger)cardDensit
  783. {
  784. if(isLan){
  785. HLog(@"云机屏幕 设置 宽:%ld 高:%ld",cardHeight,cardWidth);
  786. [_mediaStream setCardSize:cardHeight cardHeight:cardWidth cardDensity:cardDensit];
  787. [_mediaStream setVideoSize:cardHeight videoHeight:cardWidth frameRate:0];
  788. }
  789. else{
  790. HLog(@"云机屏幕 设置 宽:%ld 高:%ld",cardWidth,cardHeight);
  791. [_mediaStream setCardSize:cardWidth cardHeight:cardHeight cardDensity:cardDensit];
  792. [_mediaStream setVideoSize:cardWidth videoHeight:cardHeight frameRate:0];
  793. }
  794. }
  795. #pragma mark -- /*通知添加与移除*/
  796. - (void)addKVOObserverFun
  797. {
  798. outputVolumeKVO = YES;
  799. [[AVAudioSession sharedInstance] addObserver:self forKeyPath:@"outputVolume" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:(void *)[AVAudioSession sharedInstance]];
  800. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getPlayerBottomNavShowOrHidefun) name:getPlayerBottomNavNotification object:nil];
  801. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setPlayerFullScreenNotFun) name:setPlayerFullScreenNotification object:nil];
  802. //监听系统 前后台事件
  803. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:nil];
  804. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
  805. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
  806. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
  807. //输入密码完成
  808. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didInpuPwdOkFun) name:didInputPWDNotification object:nil];
  809. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange:) name:NetWorkChangeNotification object:nil];
  810. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(relinkWebRtcFun) name:didPingBestWebRtcIPRoomNotification object:nil];
  811. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitCloudPhoneFun) name:needToPoPCloudPhoneVCNotification object:nil];
  812. }
  813. - (void)removeKVOObserverFun
  814. {
  815. if (outputVolumeKVO)
  816. {
  817. [[AVAudioSession sharedInstance] removeObserver:self forKeyPath:@"outputVolume" context:(void *)[AVAudioSession sharedInstance]];
  818. outputVolumeKVO = NO;
  819. }
  820. [[NSNotificationCenter defaultCenter] removeObserver:self];
  821. }
  822. #pragma mark 系统音量键监听
  823. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
  824. if(context == (__bridge void *)[AVAudioSession sharedInstance])
  825. {
  826. /*音量开关打开时 允许发送指令 否则直接返回*/
  827. float newValue = [[change objectForKey:@"new"] floatValue];
  828. float oldValue = [[change objectForKey:@"old"] floatValue];
  829. //HLog(@"音量 --old: %f ---new: %f",oldValue,newValue)
  830. if (newValue > oldValue)
  831. {
  832. HLog(@"\n-----音量增加");
  833. [self didClickKeyEventFunBy:24];
  834. }
  835. else
  836. {
  837. HLog(@"\n-----音量降低");
  838. [self didClickKeyEventFunBy:25];
  839. }
  840. }
  841. }
  842. #pragma - mark - 监听网络变化
  843. - (void)networkStateChange:(NSNotification *)notification
  844. {
  845. /*处理*/
  846. KWeakSelf
  847. switch ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus)
  848. {
  849. case AFNetworkReachabilityStatusUnknown:/*网络状态未知*/
  850. {
  851. ;
  852. }
  853. break;
  854. case AFNetworkReachabilityStatusNotReachable:/*网络不可用*/
  855. {
  856. }
  857. break;
  858. case AFNetworkReachabilityStatusReachableViaWWAN:/*流量*/
  859. {
  860. mainBlock(^{
  861. [weakSelf.mediaStream setMaxBitrate:[NSNumber numberWithInteger:4*1024]];
  862. });
  863. }
  864. break;
  865. case AFNetworkReachabilityStatusReachableViaWiFi:/*WiFi*/
  866. {
  867. mainBlock(^{
  868. [weakSelf.mediaStream setMaxBitrate:[NSNumber numberWithInteger:8*1024]];
  869. });
  870. }
  871. break;
  872. default:
  873. break;
  874. }
  875. }
  876. #pragma mark 监听到云机的宽高以及屏幕方向
  877. - (void)handlUIAfterGetCloudPhoneVideoWidth:(int)videoWidth videoHeight:(int)videoHeight rotation:(int)rotation
  878. {
  879. HLog(@"云机屏幕 回调 宽:%d 高:%d 横竖屏:%d",videoWidth,videoHeight,rotation);
  880. CGFloat curRate = (CGFloat)videoWidth/(CGFloat)videoHeight;
  881. if(lastVideoWHRate == curRate){
  882. return;
  883. }
  884. didAdjusBtnType = NO;
  885. if(rotation == 0){//竖屏
  886. //切换到竖屏
  887. isLan = NO;
  888. [self player_rotateToInterfaceOrientation:UIInterfaceOrientationPortrait];
  889. [self setPoMas_makeWithImageRate:curRate];
  890. }
  891. else if(rotation == 1){//横屏
  892. //切换到横屏屏
  893. isLan = YES;
  894. [self player_rotateToInterfaceOrientation:UIInterfaceOrientationLandscapeRight];
  895. [self setLanMas_makeWithImageRate:curRate];
  896. }
  897. _didHandleRotation = YES;
  898. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  899. [self extensionAdjustBtnFrameCheckAdjustTime];
  900. });
  901. }
  902. #pragma mark WebRTC 回调 MediaStreamClientEventsDelegate
  903. #pragma mark - 宽高变化
  904. -(void)onFrameResolutionChangedFromPeerName:(NSString*)peerName videoWidth:(int)videoWidth videoHeight:(int)videoHeight rotation:(int)rotation {
  905. HLog(@"推拉流 onFrameResolutionChangedFromPeerName:%@---%d---%d--%d",peerName,videoWidth,videoHeight,rotation)
  906. [cachesFileManager writeLogsWithMsg:[[NSString alloc] initWithFormat:@"webRtcPlayer onFrameResolutionChangedFromPeerName:%@",peerName]];
  907. HLog(@"ok _mediaStream:%@",_mediaStream)
  908. mainBlock(^{
  909. [self handlUIAfterGetCloudPhoneVideoWidth:videoWidth videoHeight:videoHeight rotation:rotation];
  910. });
  911. }
  912. //code 0 成功 1失败
  913. -(void)onAuthResultFromPeerName:(NSString*)peerName code:(int)code descriptions:(NSString*)descriptions
  914. {
  915. HLog(@"onAuthResultFromPeerName:%@---%d---%@",peerName,code,descriptions)
  916. [cachesFileManager writeLogsWithMsg:[[NSString alloc] initWithFormat:@"webRtcPlayer onAuthResultFromPeerName:%d--%@",code,descriptions]];
  917. }
  918. #pragma mark 链接发生变化
  919. -(void)onChangeConnectionStateFromPeerName:(NSString*)peerName didChangeIceConnectionState:(RTCIceConnectionState)state
  920. {
  921. HLog(@"推拉流 onChangeConnectionStateFromPeerName: state:%ld",state)
  922. [cachesFileManager writeLogsWithMsg:[[NSString alloc] initWithFormat:@"webRtcPlayer onChangeConnectionStateFromPeerName:%ld",state]];
  923. _linkState = state;
  924. switch (state) {
  925. case RTCIceConnectionStateConnected:{
  926. //链接成功
  927. mainBlock(^{
  928. [self removeNewIndicator];
  929. //客户端停止写日志
  930. [ksharedAppDelegate.WebRtcLogger stop];
  931. });
  932. //PC断可能开启键盘透传 每次进入先关闭
  933. NSString *str = [RCCommandHelp commandCloseLoaclKeyboad];
  934. [[webRtcManager shareManager] send_data:str];
  935. }
  936. break;
  937. case RTCIceConnectionStateCompleted:
  938. //链接完成
  939. break;
  940. case RTCIceConnectionStateFailed:
  941. case RTCIceConnectionStateDisconnected:
  942. case RTCIceConnectionStateClosed:{
  943. if(!_didReportWebRtcFailType){//还没上报过通道链接情况
  944. _didReportWebRtcFailType = YES;
  945. [[webRtcManager shareManager] reportWebRtcRePoportTypeIsChannel:YES withStats:nil withSessionId:_webRtcPlayerSessionId];
  946. //[[addLogObject shareInstance] gotoAddLogFun];
  947. }
  948. //链接关闭
  949. [self relinkWebRtcFun];
  950. }
  951. break;
  952. default:
  953. break;
  954. }
  955. }
  956. - (void)dataChannelDidChangeFromPeerName:(NSString*)peerName State:(RTCDataChannelState)state;
  957. {
  958. HLog(@"推拉流 dataChannelDidChangeFromPeerName: state:%ld",state)
  959. [cachesFileManager writeLogsWithMsg:[[NSString alloc] initWithFormat:@"webRtcPlayer dataChannelDidChangeFromPeerName:%ld",state]];
  960. switch (state) {
  961. case RTCDataChannelStateConnecting:
  962. {
  963. }
  964. break;
  965. case RTCDataChannelStateOpen:
  966. {
  967. //链接成功
  968. [self offlineOtherPhoneFun];
  969. }
  970. break;
  971. case RTCDataChannelStateClosing:
  972. {
  973. }
  974. break;
  975. case RTCDataChannelStateClosed:
  976. {
  977. //链接断开
  978. [self relinkWebRtcFun];
  979. }
  980. break;
  981. default:
  982. break;
  983. }
  984. }
  985. -(void)onChannelDataFromPeerName:(NSString*)peerName buffer:(RTC_OBJC_TYPE(RTCDataBuffer) *)buffer
  986. {
  987. //HLog(@"onIceConnectedFromPeerName:%@",buffer.data);
  988. if(buffer && buffer.data){
  989. KWeakSelf
  990. mainBlock(^{
  991. [weakSelf handleWebRtcMsgResponseBy:buffer.data];
  992. });
  993. }
  994. }
  995. -(void)didGetStats:(NSString*)peerName stats:(RTC_OBJC_TYPE(RTCStatisticsReport) *)stats {
  996. if(!_didReportWebRtcOKType){
  997. [[webRtcManager shareManager] reportWebRtcRePoportTypeIsChannel:NO withStats:stats withSessionId:_webRtcPlayerSessionId];
  998. _didReportWebRtcOKType = YES;
  999. _didReportWebRtcFailType = NO;//链接成功后 失败要重新上报
  1000. }
  1001. //NSString *selectedCandidatePairId = nil;
  1002. /*延时数据*/
  1003. NSNumber *currentRoundTripTime = nil;
  1004. //线性增长接收包数
  1005. long packetsReceived = 0;
  1006. //视频丢包数据
  1007. long videolostData = 0;
  1008. //音频丢包数据
  1009. long audiolostData = 0;
  1010. //总丢包数据
  1011. long alllostData = 0;
  1012. //每秒帧数 ----界面展示的帧率
  1013. NSInteger framesPerSecond = 0;
  1014. //计算传输速度
  1015. long preReceive = 0;
  1016. KWeakSelf
  1017. for (NSString *key in [stats.statistics allKeys]) {
  1018. RTCStatistics *rtcStatistics = [stats.statistics objectForKey:key];
  1019. //HLog(@"hxd11111---->%@",rtcStatistics.type);
  1020. if ([rtcStatistics.type isEqualToString:@"transport"]) {
  1021. //HLog(@"传输数据---->%@",rtcStatistics.values);
  1022. double timestamp = rtcStatistics.timestamp_us;
  1023. NSNumber *bytesReceived = (NSNumber *)[rtcStatistics.values objectForKey:@"bytesReceived"];
  1024. NSNumber *packetsReceivedNumber = (NSNumber *)[rtcStatistics.values objectForKey:@"packetsReceived"];
  1025. packetsReceived = [packetsReceivedNumber longValue];
  1026. if (lastTimestamp > 0) {
  1027. long diffReceive = [bytesReceived longValue] - [lastBytesReceived longValue];
  1028. double diffTime = timestamp - lastTimestamp;
  1029. preReceive = (diffReceive / diffTime) * 1000000;
  1030. }else{
  1031. lastTimestamp = timestamp;
  1032. lastBytesReceived = bytesReceived;
  1033. }
  1034. //selectedCandidatePairId = (NSString *)[rtcStatistics.values objectForKey:@"selectedCandidatePairId"];
  1035. }
  1036. /*丢包数据*/
  1037. if ([rtcStatistics.type isEqualToString:@"inbound-rtp"]) {
  1038. NSString *kind = (NSString *)[rtcStatistics.values objectForKey:@"kind"];
  1039. if([kind isEqualToString:@"video"]){
  1040. NSNumber*videolostDataNumber = (NSNumber *)[rtcStatistics.values objectForKey:@"packetsLost"];
  1041. videolostData = [videolostDataNumber longValue];
  1042. HLog(@"丢包率 视频频%@",videolostDataNumber)
  1043. NSNumber*framesPerSecondNumber = (NSNumber *)[rtcStatistics.values objectForKey:@"framesPerSecond"];
  1044. framesPerSecond = [framesPerSecondNumber integerValue];
  1045. }
  1046. else if([kind isEqualToString:@"audio"]){
  1047. NSNumber*audiolostDataNumber = (NSNumber *)[rtcStatistics.values objectForKey:@"packetsLost"];
  1048. audiolostData = [audiolostDataNumber longValue];
  1049. HLog(@"丢包率 音频%@",audiolostDataNumber)
  1050. }
  1051. }
  1052. for (NSString *keyin in [rtcStatistics.values allKeys]) {
  1053. if ([keyin isEqualToString:@"currentRoundTripTime"]){
  1054. /*延时数据*/
  1055. currentRoundTripTime = (NSNumber*)[rtcStatistics.values objectForKey:@"currentRoundTripTime"];
  1056. //[self updateAutoRateAndNetWorkStatesWithDelatyMS:(NSInteger)currentRoundTripTime.floatValue*1000];
  1057. break;
  1058. }
  1059. }
  1060. }
  1061. //网络延迟, 丢包率,FPS,网速 分辨率 流量
  1062. //延时数据
  1063. NSInteger delayedMS = (NSInteger)(currentRoundTripTime.floatValue*1000);
  1064. //计算上次报道到这一次的丢包率---------界面展示百分比丢包率
  1065. double curlostTimestamp = [iTools getNowTimeStamp];
  1066. if(prelostTimestamp == 0 || (curlostTimestamp - prelostTimestamp >= 3)){
  1067. long allPacketsReceived = packetsReceived - lasPacketsReceived;
  1068. if(allPacketsReceived < 0){//异常处理
  1069. lastAlllostData = 0;
  1070. lasPacketsReceived = 0;
  1071. prelostRate = 0;
  1072. }
  1073. else{
  1074. alllostData = audiolostData + videolostData;
  1075. double NsecondLostData = (alllostData - lastAlllostData) *1.0;
  1076. double NsecondReceivedData = (allPacketsReceived + (alllostData - lastAlllostData));
  1077. if(NsecondReceivedData > 0){
  1078. double lostRate = (NsecondLostData / NsecondReceivedData) *100;
  1079. //记录上一次丢包数
  1080. lastAlllostData = alllostData;
  1081. //记录上一次接收包数
  1082. lasPacketsReceived = packetsReceived;
  1083. prelostRate = lostRate;
  1084. prelostTimestamp = curlostTimestamp;
  1085. }
  1086. //FPS
  1087. __block NSString*lostDataStr = [[NSString alloc] initWithFormat:@"总包数:%ld --总丢包数:%ld--3秒接受到包数:%ld---3秒丢包数:%ld---3秒丢包率:%0.2f%%",lasPacketsReceived,lastAlllostData,(NSInteger)NsecondReceivedData,(NSInteger)NsecondLostData,prelostRate];
  1088. webrtcServerModel * webrtcServerMod = ksharedAppDelegate.bestWebrtcServerModel;
  1089. NSMutableString *signallingUrl = [[NSMutableString alloc] initWithFormat:@"当前使用:%@:%@--\n%@:%@--%.0fms\n\n",webrtcServerMod.signallingIp,webrtcServerMod.signallingPort,webrtcServerMod.turnIp,webrtcServerMod.turnPort,webrtcServerMod.delayedms];
  1090. for (webrtcServerModel *model in ksharedAppDelegate.DeviceWebRtcMsgMod.data.webrtcServerList) {
  1091. NSString *curStr = [[NSMutableString alloc] initWithFormat:@"%@:%@--\n%@:%@--%.0fms\n",model.signallingIp,model.signallingPort,model.turnIp,model.turnPort,model.delayedms];
  1092. [signallingUrl appendString:curStr];
  1093. }
  1094. lostDataStr = [[NSString alloc] initWithFormat:@"%@\n%@",lostDataStr,signallingUrl];
  1095. mainBlock(^{
  1096. self->_testLostLabel.text = lostDataStr;
  1097. });
  1098. }
  1099. }
  1100. //网速 传输数据速度
  1101. NSString *netDataSpeedStr = @"";
  1102. if(preReceive/1024.0 > 1024){
  1103. netDataSpeedStr = [NSString stringWithFormat:@"%.01fMB/s",preReceive/1024.0/1024.0];
  1104. }
  1105. else{
  1106. netDataSpeedStr = [NSString stringWithFormat:@"%ldKB/s",preReceive/1024];
  1107. }
  1108. mainBlock(^{
  1109. if(weakSelf.playerSetV){
  1110. [weakSelf updateControlBtnBgImageWith:delayedMS];
  1111. [weakSelf.playerSetV setWebRctMsgBydelayed:delayedMS withPacketLoss:self->prelostRate withSpeed:netDataSpeedStr withFPS:@""];
  1112. }
  1113. });
  1114. }
  1115. - (void)connectionChange:(NSString*)peerName
  1116. didChangeLocalCandidate:(RTC_OBJC_TYPE(RTCIceCandidate) *)local
  1117. remoteCandidate:(RTC_OBJC_TYPE(RTCIceCandidate) *)remote
  1118. lastReceivedMs:(int)lastDataReceivedMs
  1119. changeReason:(NSString *)reason
  1120. {
  1121. //HLog(@"webRtc P2P didChangeLocalCandidate")
  1122. [[webRtcManager shareManager] reportWebRtcRePoportTypeIsChannel:YES withLocal:local remoteCandidate:remote withSessionId:self.webRtcPlayerSessionId];
  1123. }
  1124. #pragma mark 更新悬浮图标的颜色
  1125. - (void)updateControlBtnBgImageWith:(NSInteger)delayedMS{
  1126. if (delayedMS < 50) {
  1127. if(preDelayedMS > 0 && preDelayedMS < 50){
  1128. return;//没有变化 不处理
  1129. }
  1130. [controlBtn setBackgroundImage:[UIImage imageNamed:@"you_icon"] forState:(UIControlStateNormal)];
  1131. }
  1132. else if (delayedMS < 100){
  1133. if(preDelayedMS > 50 && preDelayedMS < 100){
  1134. return;//没有变化 不处理
  1135. }
  1136. [controlBtn setBackgroundImage:[UIImage imageNamed:@"you_yellow"] forState:(UIControlStateNormal)];
  1137. }
  1138. else{
  1139. if( preDelayedMS > 100){
  1140. return;//没有变化 不处理
  1141. }
  1142. [controlBtn setBackgroundImage:[UIImage imageNamed:@"you_red"] forState:(UIControlStateNormal)];
  1143. }
  1144. preDelayedMS = delayedMS;
  1145. }
  1146. #pragma mark 收到的webrtc消息处理
  1147. - (void)handleWebRtcMsgResponseBy:(NSData*)message
  1148. {
  1149. if([message isKindOfClass:[NSMutableString class]] || [message isKindOfClass:[NSString class]])
  1150. {
  1151. message = [(NSString *)message dataUsingEncoding:(NSUTF8StringEncoding)];
  1152. }
  1153. NSError *error = nil;
  1154. NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:message options:NSJSONReadingMutableContainers error:&error];
  1155. HLog(@"webRtc 音视频推拉流 通道接收消息:------------------%@",dataDict);
  1156. if(!dataDict){
  1157. //[weakSelf handleDownloadResponseFunBy:message];
  1158. return;
  1159. }
  1160. if(![dataDict isKindOfClass:[NSDictionary class]]){
  1161. //[__NSCFString allKeys] unrecognized selector sent to ins
  1162. return;
  1163. }
  1164. if(![[dataDict allKeys] containsObject:@"type"]){
  1165. return;
  1166. }
  1167. NSString *messageType = dataDict[@"type"];
  1168. if ([messageType isEqualToString:@"login"]) {
  1169. if([[dataDict allKeys] containsObject:@"value"]){
  1170. NSString *value = dataDict[@"value"];
  1171. [self LogoutByOtherFun:value];
  1172. }
  1173. }
  1174. }
  1175. //延迟系统触摸事件
  1176. - (UIRectEdge)preferredScreenEdgesDeferringSystemGestures{
  1177. return UIRectEdgeAll;
  1178. }
  1179. #pragma mark 检测盒子的心跳情况
  1180. - (void)checkBoxHeartbeatFun
  1181. {
  1182. //1.隐私模式密码界面 3秒检测一次是否输入完成密码了
  1183. if(ksharedAppDelegate.isDidShowPwdType){
  1184. KWeakSelf
  1185. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1186. [weakSelf checkBoxHeartbeatFun];
  1187. });
  1188. return;
  1189. }
  1190. // [[BoxHeartbeatAlertTool shareInstance] showBoxHeartbeatAlertFun:1 didClickBut:^(NSInteger tag) {
  1191. //
  1192. // }];
  1193. if(ksharedAppDelegate.isWebSockLinkOKAginType && ksharedAppDelegate.cloudPhoneExtraFileListMod){
  1194. return;
  1195. }
  1196. NSMutableDictionary *paraDict = [NSMutableDictionary new];
  1197. KWeakSelf
  1198. [[netWorkManager shareInstance] CommonGetWithCallBackCode:queryHeartbeat Parameters:paraDict success:^(id _Nonnull responseObject){
  1199. queryHeartbeatModel *heartbeatMod = [[queryHeartbeatModel alloc] initWithDictionary:responseObject error:nil];
  1200. if(heartbeatMod && heartbeatMod.data){
  1201. [weakSelf checkBoxHeartbeatToShowPopViewFunBy:heartbeatMod];
  1202. }
  1203. } failure:^(NSError * _Nonnull error) {
  1204. }];
  1205. }
  1206. #pragma mark 根据盒子的心跳情况 显示异常谈了
  1207. - (void)checkBoxHeartbeatToShowPopViewFunBy:(queryHeartbeatModel*)heartbeatMod
  1208. {
  1209. if(!heartbeatMod || !heartbeatMod.data){
  1210. return;
  1211. }
  1212. if (!heartbeatMod.data.frpStatus
  1213. &&!heartbeatMod.data.hostAgentStatus
  1214. &&!heartbeatMod.data.containerAgentStatus) {//全部异常
  1215. [[BoxHeartbeatAlertTool shareInstance] showBoxHeartbeatAlertFun:1 didClickBut:^(NSInteger tag) {
  1216. }];
  1217. }
  1218. else if (heartbeatMod.data.hostAgentStatus
  1219. && !heartbeatMod.data.frpStatus
  1220. && !heartbeatMod.data.containerAgentStatus) {//frp异常
  1221. [[BoxHeartbeatAlertTool shareInstance] showBoxHeartbeatAlertFun:2 didClickBut:^(NSInteger tag) {
  1222. }];
  1223. }
  1224. else{//原来的逻辑
  1225. [self showLinkPhoneErrorFun];
  1226. }
  1227. }
  1228. @end