webRtcPlayerViewController.m 53 KB

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