webRtcPlayerViewController.m 52 KB

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