webRtcPlayerViewController.m 54 KB

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