webRtcPlayerViewController.m 48 KB

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