webRtcPlayerViewController.m 47 KB

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