webRtcPlayerViewController.m 53 KB

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