webRtcPlayerViewController.m 55 KB

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