webRtcPlayerViewController.m 48 KB

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