webRtcPlayerViewController.m 49 KB

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