webRtcPlayerViewController.m 47 KB

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