webRtcPlayerViewController.m 53 KB

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