webRtcPlayerViewController.m 54 KB

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