webRtcPlayerViewController.m 56 KB

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