webRtcPlayerViewController.m 49 KB

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