webRtcPlayerViewController.m 49 KB

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