webRtcPlayerViewController.m 49 KB

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