webRtcPlayerViewController.m 48 KB

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