webRtcPlayerViewController.m 47 KB

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