webRtcPlayerViewController.m 46 KB

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