BGTPublishController.m 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613
  1. //
  2. // BGTPublishController.m
  3. // BuguLive
  4. //
  5. // Created by xfg on 16/12/5.
  6. // Copyright © 2016年 xfg. All rights reserved.
  7. //
  8. #import "BGTPublishController.h"
  9. #import <Foundation/Foundation.h>
  10. #import <TXLiteAVSDK_Professional/TXLiveSDKTypeDef.h>
  11. #import <TXLiteAVSDK_Professional/TXLiveBase.h>
  12. //#import <TXLiteAVSDK_Professional/COSClient.h>
  13. #import <sys/types.h>
  14. #import <sys/sysctl.h>
  15. #import <UIKit/UIKit.h>
  16. #import <mach/mach.h>
  17. /////////////////// TiFaceSDK 添加 开始 ///////////////////
  18. #import "TiSDKInterface.h"
  19. //#import "TiUIView.h"
  20. #import "BeautySettingPanel.h"
  21. /////////////////// TiFaceSDK 添加 结束 ///////////////////
  22. //声网dev
  23. #import "AgoraPushUtils.h"
  24. #import "UIView+CustomAutoLayout.h"
  25. #import "BogoPkProgressModel.h"
  26. // 清晰度定义
  27. #define HD_LEVEL_720P 1 // 1280 * 720
  28. #define HD_LEVEL_540P 2 // 960 * 540
  29. #define HD_LEVEL_360P 3 // 640 * 360
  30. #define HD_LEVEL_360_PLUS 4 // 640 * 360 且开启码率自适应
  31. #define kRePublishTime 3 // 断开后重新尝试的次数
  32. #import "UserView.h"
  33. //语音连麦
  34. #import "VoiceLianmaiView.h"
  35. #import "VoiceLianmaiUserModel.h"
  36. @interface BGTPublishController ()<TXLivePushListener,TXLivePlayListener,TXVideoCustomProcessDelegate,TiUIManagerDelegate,BeautySettingPanelDelegate,UserViewDelegate,TRTCCloudDelegate>{
  37. BeautySettingPanel *_beautyPanel; // 美颜控件
  38. }
  39. /////////////// TiSDK 添加 开始 /////////////
  40. //@property(nonatomic, strong) TiSDKManager *tiSDKManager;
  41. //@property(nonatomic, strong) TiUIView *tiUIView;
  42. /////////////// TiSDK 添加 结束 /////////////
  43. @property (nonatomic,copy) NSString * txTaskId;
  44. @end
  45. @implementation BGTPublishController
  46. {
  47. //声网dev
  48. BOOL unpublishing;
  49. UIView *userListView;
  50. UserView *userView1;
  51. UserView *userView2;
  52. UserView *userView3;
  53. NSMutableArray <NSString *> *lianMaiuser;
  54. NSMutableArray <NSString *> *linkedUsers;//已经连接的用户
  55. NSString *PKRtmpURL;
  56. //是否已经混流了
  57. BOOL _isMix;
  58. }
  59. - (void)endLive
  60. {
  61. [[NSNotificationCenter defaultCenter] removeObserver:self];
  62. [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(startPushRtmpLiveMethod) object:nil];
  63. }
  64. - (void)dealloc
  65. {
  66. NSLog(@"%s",__func__);
  67. [[NSNotificationCenter defaultCenter] removeObserver:self];
  68. // if (self.tiSDKManager) {
  69. // [self.tiSDKManager destroy];
  70. // self.tiSDKManager = nil;
  71. // }
  72. }
  73. - (void)clickUserView:(UserView *)view
  74. {
  75. }
  76. - (void)clickCloseBtn:(UserView *)view
  77. {
  78. // view.uid
  79. //是否断开连麦
  80. }
  81. - (void)viewDidLoad
  82. {
  83. [super viewDidLoad];
  84. unpublishing = NO;
  85. ///////////// TiSDK 添加 开始 ////////////
  86. lianMaiuser = [NSMutableArray array];
  87. linkedUsers = [NSMutableArray array];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMainSwitchButtonClick:) name:@"onMainSwitchButtonClick" object:nil];
  89. //#error TiSDK Key, 与包名对应,请联系商务获取
  90. NSString* key = [GlobalVariables sharedInstance].appModel.bogo_beauty_key;
  91. if([BGUtils isBlankString:key])
  92. {
  93. //这里写上那个key
  94. key = @"517a990947274dd8b51e1525feb0fb79";
  95. // [[BGHUDHelper sharedInstance] tipMessage:ASLocalizedString(@"美颜key为空,请尝试重新打开app获取!")];
  96. }
  97. else
  98. {
  99. // NSString* key = [GlobalVariables sharedInstance].appModel.bogo_beauty_key;
  100. //
  101. // // NSString* key = @"";
  102. //
  103. //// [[TiSDKManager shareManager] destroy];
  104. //// [[TiUIManager shareManager] destroy]; // TiSDK开源UI窗口对象资源释放
  105. // [TiSDK init:key CallBack:^(InitStatus initStatus) {
  106. // [[NSNotificationCenter defaultCenter] postNotificationName:@"TiSDKInitStatusNotification" object:nil];
  107. // }];
  108. //
  109. // // [[TiUIManager shareManager] loadToSuperview:self.view];
  110. // [TiUIManager shareManager].showsDefaultUI = YES;
  111. // [[TiUIManager shareManager]loadToWindowDelegate:self];
  112. }
  113. [self initConfig];
  114. ///////////// TiSDK 添加 结束 /////////////
  115. //loading imageview
  116. float width = 34;
  117. float height = 34;
  118. float offsetX = (self.view.frame.size.width - width) / 2;
  119. float offsetY = (self.view.frame.size.height - height) / 2;
  120. NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:[UIImage imageNamed:@"loading_image0.png"],[UIImage imageNamed:@"loading_image1.png"],[UIImage imageNamed:@"loading_image2.png"],[UIImage imageNamed:@"loading_image3.png"],[UIImage imageNamed:@"loading_image4.png"],[UIImage imageNamed:@"loading_image5.png"],[UIImage imageNamed:@"loading_image6.png"],[UIImage imageNamed:@"loading_image7.png"], nil];
  121. _loadingImageView = [[UIImageView alloc] initWithFrame:CGRectMake(offsetX, offsetY, width, height)];
  122. _loadingImageView.animationImages = array;
  123. _loadingImageView.animationDuration = 1;
  124. _loadingImageView.hidden = YES;
  125. [self.view addSubview:_loadingImageView];
  126. }
  127. -(void)onMainSwitchButtonClick:(NSNotificationCenter *)sender{
  128. [[TiUIManager shareManager]showMainMenuView];
  129. _beautyPanel.hidden = NO;
  130. // [self.tiUIView onMainSwitchButtonClick:nil];
  131. }
  132. - (void)adjustPlayItemVoiceUserList:(NSArray <VoiceLianmaiUserModel * > *)userlist
  133. {
  134. NSLog(@"刷新语音连麦视图");
  135. NSLog(@"%@",userlist);
  136. userView1.hidden = YES;
  137. userView2.hidden = YES;
  138. userView3.hidden = YES;
  139. // NSMutableArray *needAddLianMaiUser = [NSMutableArray array];//需要连麦的列表
  140. // NSMutableArray *needDelLianMaiUser = [NSMutableArray array];//需要删除的列表
  141. //
  142. //
  143. for (int i=0; i<userlist.count; i++) {
  144. if(i == 0)
  145. {
  146. userView1.hidden = NO;
  147. userView1.userName.text = userlist[i].nick_name;
  148. userView1.uid = userlist[i].user_id;
  149. [self.trtcCloud startRemoteView:userView1.uid streamType:TRTCVideoStreamTypeBig view:userView1.videoView];
  150. }
  151. else if(i == 1)
  152. {
  153. userView2.hidden = NO;
  154. userView2.userName.text = userlist[i].nick_name;
  155. userView2.uid = userlist[i].user_id;
  156. TRTCRenderParams *params = [[TRTCRenderParams alloc] init];
  157. // 画面镜像模式
  158. params.mirrorType = TRTCVideoMirrorTypeDisable;
  159. // 画面填充模式
  160. params.fillMode = TRTCVideoFillMode_Fill;
  161. // 画面旋转角度
  162. params.rotation = TRTCVideoRotation_0;
  163. // 设置远端画面的渲染模式
  164. [self.trtcCloud setRemoteRenderParams:userView2.uid streamType:TRTCVideoStreamTypeBig params:params];
  165. [self.trtcCloud startRemoteView:userView1.uid streamType:TRTCVideoStreamTypeBig view:userView2.videoView];
  166. // AgoraRtcVideoCanvas *videoCanvas = [[AgoraRtcVideoCanvas alloc] init];
  167. // videoCanvas.uid = userlist[i].user_id.intValue;
  168. // videoCanvas.renderMode = AgoraVideoRenderModeHidden;
  169. // videoCanvas.view = userView2.videoView;
  170. // [self.agoraKit setupRemoteVideo:videoCanvas];
  171. }
  172. else if(i == 2)
  173. {
  174. userView3.hidden = NO;
  175. userView3.userName.text = userlist[i].nick_name;
  176. userView3.uid = userlist[i].user_id;
  177. TRTCRenderParams *params = [[TRTCRenderParams alloc] init];
  178. // 画面镜像模式
  179. params.mirrorType = TRTCVideoMirrorTypeDisable;
  180. // 画面填充模式
  181. params.fillMode = TRTCVideoFillMode_Fill;
  182. // 画面旋转角度
  183. params.rotation = TRTCVideoRotation_0;
  184. // 设置远端画面的渲染模式
  185. [self.trtcCloud setRemoteRenderParams:userView3.uid streamType:TRTCVideoStreamTypeBig params:params];
  186. [self.trtcCloud startRemoteView:userView1.uid streamType:TRTCVideoStreamTypeBig view:userView3.videoView];
  187. // AgoraRtcVideoCanvas *videoCanvas = [[AgoraRtcVideoCanvas alloc] init];
  188. // videoCanvas.uid = userlist[i].user_id.intValue;
  189. // videoCanvas.renderMode = AgoraVideoRenderModeHidden;
  190. // videoCanvas.view = userView3.videoView;
  191. // [self.agoraKit setupRemoteVideo:videoCanvas];
  192. }
  193. }
  194. if (userlist.count <= 0) {
  195. return;
  196. }
  197. NSArray *subView = userListView.subviews;
  198. // for (int i=0; i<subView.count; i++) {
  199. // UIView *itemView = subView[i];
  200. // [itemView mas_remakeConstraints:^(MASConstraintMaker *make) {
  201. //
  202. // }];
  203. // }
  204. NSMutableArray *realViewArr = [NSMutableArray array];
  205. for (int i=0; i<subView.count; i++) {
  206. UIView *itemView = subView[i];
  207. if(itemView.hidden == NO)
  208. {
  209. [realViewArr addObject:itemView];
  210. }
  211. }
  212. int userViewWidth = 120;
  213. int userViewHeight = userViewWidth * 1.6;
  214. [userListView mas_remakeConstraints:^(MASConstraintMaker *make) {
  215. make.width.equalTo(@(userViewWidth));
  216. make.height.equalTo(@(userViewHeight * realViewArr.count));
  217. make.bottom.equalTo(self.view).offset(-80);
  218. make.right.equalTo(self.view).offset(-20);
  219. make.height.equalTo(@(realViewArr.count * userViewHeight));
  220. }];
  221. if(realViewArr.count > 1)
  222. {
  223. [realViewArr mas_remakeConstraints:^(MASConstraintMaker *make) {
  224. make.height.equalTo(@(userViewHeight));
  225. make.width.equalTo(@(userViewWidth));
  226. }];
  227. [realViewArr mas_distributeViewsAlongAxis:MASAxisTypeVertical withFixedItemLength:userViewHeight leadSpacing:3 tailSpacing:3];
  228. }
  229. else if(realViewArr.count == 1)
  230. {
  231. [realViewArr[0] mas_remakeConstraints:^(MASConstraintMaker *make) {
  232. make.bottom.equalTo(userListView);
  233. make.height.equalTo(@(userViewHeight));
  234. make.width.equalTo(@(userViewWidth));
  235. }];
  236. }
  237. }
  238. - (void)adjustPlayItemAgora:(TLiveMickListModel *)mickListModel;
  239. {
  240. // [lianMaiuser removeObjectAtIndex:removeIndex];
  241. // [lianMaiuser removeAllObjects];
  242. __block BOOL isfind = NO;
  243. NSMutableArray *allUserIds = [NSMutableArray array];
  244. for (int i=0; i<mickListModel.list_lianmai.count; i++) {
  245. //如果之前有了就不处理他了
  246. TLiveMickModel *mickModel = mickListModel.list_lianmai[i];
  247. if(![lianMaiuser containsObject:mickModel.user_id])
  248. {
  249. [lianMaiuser addObject:mickModel.user_id];
  250. isfind = YES;
  251. }
  252. [allUserIds addObject:mickModel.user_id];
  253. }
  254. [lianMaiuser enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  255. if(![allUserIds containsObject:obj])
  256. {
  257. isfind = YES;
  258. [lianMaiuser removeObject:obj];
  259. }
  260. }];
  261. if(isfind)
  262. {
  263. [self reloduserListView];
  264. }
  265. }
  266. #pragma mark - 初始化
  267. - (void)initializeAgoraEngine {
  268. self.trtcCloud = [TRTCCloud sharedInstance];
  269. [self.trtcCloud addDelegate:self];
  270. }
  271. - (void)joinChannel {
  272. // 设置本地画面的预览模式:开启左右镜像,设置画面为填充模式
  273. TRTCRenderParams *param = [[TRTCRenderParams alloc] init];
  274. param.fillMode = TRTCVideoFillMode_Fill;
  275. param.mirrorType = TRTCVideoMirrorTypeDisable;
  276. [self.trtcCloud setLocalRenderParams:param];
  277. // 启动本地摄像头的预览(localCameraVideoView 是用于渲染本地渲染画面的控件)
  278. [self.trtcCloud startLocalPreview:YES view:_preViewContainer];
  279. // 通过 TXDeviceManager 开启自动对焦并将闪光灯打开
  280. TXDeviceManager *manager = [self.trtcCloud getDeviceManager];
  281. if ([manager isAutoFocusEnabled]) {
  282. [manager enableCameraAutoFocus:YES];
  283. }
  284. //开启闪光灯,手电筒
  285. // [manager enableCameraTorch:YES];
  286. // 开启麦克风采集,并设置当前场景为:音乐模式(高保真采集、低音质损失,推荐配合专业声卡使用)
  287. [self.trtcCloud startLocalAudio:TRTCAudioQualityMusic];
  288. TRTCParams *params = [[TRTCParams alloc] init];
  289. // 以字符串房间号为例
  290. params.roomId = self.roomIDStr.intValue;
  291. params.userId = [IMAPlatform sharedInstance].host.userId;
  292. // 从业务后台获取到的 UserSig
  293. params.userSig = [IMALoginParam loadFromLocal].userSig;
  294. // 替换成您的 SDKAppID
  295. params.sdkAppId = TXSDKAppID;
  296. // 根据需要指定用户角色
  297. params.role = TRTCRoleAnchor;
  298. // 根据需要指定场景
  299. [self.trtcCloud enterRoom:params appScene:TRTCAppSceneLIVE];
  300. TRTCVideoEncParam *videoEncParam = [[TRTCVideoEncParam alloc] init];
  301. videoEncParam.videoFps = 24;
  302. videoEncParam.resMode = TRTCVideoResolutionModePortrait;
  303. videoEncParam.videoResolution = TRTCVideoResolution_960_540;
  304. [self.trtcCloud setVideoEncoderParam:videoEncParam];
  305. }
  306. #pragma mark ******************* 腾讯代理方法 *******************
  307. - (void)onEnterRoom:(NSInteger)result {
  308. if (result > 0) {
  309. // result 代表加入房间所消耗的时间(毫秒)
  310. // [self toastTip:@"Enter room succeed!"];
  311. [self startRtmpStreaming:self.pushUrlStr];
  312. } else {
  313. // result 代表进房失败的错误码
  314. [self toastTip:@"Enter room failed!"];
  315. }
  316. AppDelegate.sharedAppDelegate.isEnterLiveVC = YES;
  317. }
  318. //远程静音视频或者音频
  319. - (void)onUserAudioAvailable:(NSString *)userId available:(BOOL)available {
  320. if (available) {
  321. // 发布音频
  322. } else {
  323. // 取消发布音频
  324. }
  325. NSArray *subView = userListView.subviews;
  326. for (int i=0; i<subView.count; i++) {
  327. UserView *itemView = subView[i];
  328. if(itemView.uid == userId)
  329. {
  330. if(available == NO)
  331. {
  332. NSLog(@"%@ 静音",userId);
  333. }
  334. }
  335. }
  336. }
  337. #pragma mark - //功能描述:某远端用户发布/取消了主路视频画面 取消或者开始连麦
  338. - (void)onUserVideoAvailable:(NSString *)userId available:(BOOL)available {
  339. if (available) {
  340. // 发布视频
  341. } else {
  342. // 取消发布视频
  343. }
  344. NSArray *subView = userListView.subviews;
  345. for (int i=0; i<subView.count; i++) {
  346. UserView *itemView = subView[i];
  347. if(itemView.uid == userId)
  348. {
  349. if(available == NO)
  350. {
  351. NSLog(@"%@ 关闭视频",userId);
  352. itemView.muteVideoView.hidden = NO;
  353. // itemView.videoView.hidden = YES;
  354. }
  355. else
  356. {
  357. NSLog(@"%@ 打开视频",userId);
  358. itemView.muteVideoView.hidden = YES;
  359. // itemView.videoView.hidden = NO;
  360. }
  361. }
  362. }
  363. }
  364. //功能描述:有用户加入当前房间
  365. // 远端用户加入频道时,会触发该回调
  366. - (void)onRemoteUserEnterRoom:(NSString *)userId {
  367. NSLog(@"用户加入房间 %@",userId);
  368. //如果正在pk混流pk
  369. #warning 暂时注释,后续确认是否需要
  370. // if(self.pkTranscodin)
  371. // {
  372. // [self startPKRtmpStreaming:PKRtmpURL];
  373. //
  374. // }
  375. // else
  376. {
  377. // [self.agoraKit updateRtmpTranscoding:self.transcoding];
  378. [self updatePublishMediaStream];
  379. }
  380. [self updateUser];
  381. // [lianMaiuser addObject:StringFromInt(uid)];
  382. // [self reloduserListView];
  383. // AgoraRtcVideoCanvas *videoCanvas = [[AgoraRtcVideoCanvas alloc] init];
  384. // videoCanvas.uid = uid;
  385. // videoCanvas.renderMode = AgoraVideoRenderModeHidden;
  386. // videoCanvas.view = userView1;
  387. // // 设置远端视图
  388. // [self.agoraKit setupRemoteVideo:videoCanvas];
  389. }
  390. - (void)updatePublishMediaStream {
  391. // 媒体流发布的目标地址
  392. TRTCPublishTarget* target = [[TRTCPublishTarget alloc] init];
  393. // 目标地址设定为旁路转推到 CDN
  394. target.mode = TRTCPublishMixStreamToCdn;
  395. TRTCPublishCdnUrl* cdnUrl = [[TRTCPublishCdnUrl alloc] init];
  396. // 拼接发布到直播服务商的推流地址(RTMP 格式)
  397. cdnUrl.rtmpUrl = self.pushUrlStr;
  398. // 腾讯云直播推流地址为 true,第三方为 false
  399. cdnUrl.isInternalLine = YES;
  400. NSMutableArray* cdnUrlList = [NSMutableArray array];
  401. // 可以添加多个 CDN 推流地址
  402. [cdnUrlList addObject:cdnUrl];
  403. target.cdnUrlList = cdnUrlList;
  404. [self.trtcCloud updatePublishMediaStream:self.txTaskId publishTarget:target encoderParam:nil mixingConfig:nil];
  405. }
  406. - (void)onRemoteUserLeaveRoom:(NSString *)userId reason:(NSInteger)reason {
  407. // [self.agoraKit updateRtmpTranscoding:self.transcoding];
  408. [self updatePublishMediaStream];
  409. // NSLog(@"用户加入房间");
  410. // int removeIndex = 0;
  411. // BOOL isFind = NO;
  412. // for (int i = 0; i < lianMaiuser.count; i++) {
  413. // if(i == lianMaiuser[i].intValue)
  414. // {
  415. // removeIndex = i;
  416. // isFind = YES;
  417. // }
  418. // }
  419. // if(isFind)
  420. // {
  421. // [lianMaiuser removeObjectAtIndex:removeIndex];
  422. // [self reloduserListView];
  423. // }
  424. NSLog(@"用户离开");
  425. }
  426. //功能描述:请求跨房通话的结果回调
  427. - (void)onConnectOtherRoom:(NSString *)userId errCode:(TXLiteAVError)errCode errMsg:(NSString *)errMsg{
  428. NSLog(@"channelMediaRelayStateDidChange state %ld --error %@",(long)errCode,errMsg);
  429. }
  430. //我们可以让自己的类继承TRTCCloudDelegate,并重载 onError 函数,最后将 this 指针通过 TRTCCCloud 的 delegate 属性设置给 SDK,就可以在当前类中监听来自 SDK 的回调事件了。
  431. // 监听 SDK 的事件,并对“摄像头未被授权”等错误进行日志打印
  432. - (void)onError:(TXLiteAVError)errCode
  433. errMsg:(nullable NSString *)errMsg
  434. extInfo:(nullable NSDictionary *)extInfo {
  435. if (ERR_CAMERA_NOT_AUTHORIZED == errCode) {
  436. NSString *errorInfo = @"Current application is not authorized to use the camera:";
  437. errorInfo = [errorInfo stringByAppendingString:errMsg];
  438. NSLog(@"腾讯直播报错日志:%@",errorInfo);
  439. [self toastTip:errorInfo];
  440. }
  441. }
  442. // 如果切换角色失败,onSwitchRole 回调的错误码便不是 0
  443. // If switching operation failed, the error code of the 'onSwitchRole' is not zero
  444. - (void)onSwitchRole:(TXLiteAVError)errCode errMsg:(nullable NSString *)errMsg {
  445. if (errCode != 0) {
  446. NSLog(@"Switching operation failed... ");
  447. }
  448. }
  449. //开始发布媒体流的事件回调
  450. - (void)onStartPublishMediaStream:(NSString *)taskId code:(int)code message:(NSString *)message extraInfo:(nullable NSDictionary *)extraInfo {
  451. self.txTaskId = taskId;
  452. }
  453. // 离开房间事件回调
  454. - (void)onExitRoom:(NSInteger)reason {
  455. if (reason == 0) {
  456. NSLog(@"主动调用 exitRoom 退出房间");
  457. } else if (reason == 1) {
  458. NSLog(@"被服务器踢出当前房间");
  459. } else if (reason == 2) {
  460. NSLog(@"当前房间整个被解散");
  461. }
  462. if (self.leaveRoomBlockSuccess) {
  463. self.leaveRoomBlockSuccess();
  464. }
  465. AppDelegate.sharedAppDelegate.isEnterLiveVC = NO;
  466. }
  467. #pragma mark ******************* 腾讯代理方法 end *******************
  468. -(void)startPKRtmpStreaming:(NSString *)rtmp
  469. {
  470. // [self.agoraKit startRtmpStreamWithTranscoding:rtmp transcoding:self.pkTranscodin];
  471. // 功能描述:开始发布媒体流
  472. [self startRtmpStreaming:rtmp];
  473. }
  474. -(void)startRtmpStreaming:(NSString *)rtmp
  475. {
  476. // self.transcoding = [AgoraPushUtils getLiveHostTranscoding:[IMAPlatform sharedInstance].host.userId];
  477. // [self.agoraKit startRtmpStreamWithTranscoding:rtmp transcoding:self.transcoding];
  478. // 媒体流发布的目标地址
  479. TRTCPublishTarget* target = [[TRTCPublishTarget alloc] init];
  480. // 目标地址设定为旁路转推到 CDN
  481. target.mode = TRTCPublishBigStreamToCdn;
  482. TRTCPublishCdnUrl* cdnUrl = [[TRTCPublishCdnUrl alloc] init];
  483. // 拼接发布到直播服务商的推流地址(RTMP 格式)
  484. cdnUrl.rtmpUrl = rtmp;
  485. // 腾讯云直播推流地址为 true,第三方为 false
  486. cdnUrl.isInternalLine = YES;
  487. NSMutableArray* cdnUrlList = [NSMutableArray array];
  488. // 可以添加多个 CDN 推流地址
  489. [cdnUrlList addObject:cdnUrl];
  490. target.cdnUrlList = cdnUrlList;
  491. // 如果需要混流
  492. TRTCStreamMixingConfig *config = [[TRTCStreamMixingConfig alloc] init];
  493. // if (self.mixUserList.count) {
  494. NSMutableArray<TRTCUser *> *userList = [NSMutableArray array];
  495. NSMutableArray<TRTCVideoLayout *> *layoutList = [NSMutableArray array];
  496. // for (int i = 1; i < MIN(self.mixUserList.count, 16); i++) {
  497. // TRTCUser *user = [[TRTCUser alloc] init];
  498. // // 整型房间号为 intRoomId
  499. // user.roomId = self.roomId.intValue;
  500. // user.userId = self.mixUserList[i];
  501. // [userList addObject:user];
  502. //
  503. // TRTCVideoLayout *layout = [[TRTCVideoLayout alloc] init];
  504. // if ([self.mixUserList[i] isEqualToString:self.userId]) {
  505. // // 主播画面布局
  506. // layout.rect = CGRectMake(0, 0, 540, 960);
  507. // layout.zOrder = 0;
  508. // } else {
  509. // // 连麦观众画面布局
  510. // layout.rect = CGRectMake(400, 5 + i * 245, 135, 240);
  511. // layout.zOrder = 1;
  512. // }
  513. // layout.fixedVideoUser = user;
  514. // layout.fixedVideoStreamType = TRTCVideoStreamTypeBig;
  515. // [layoutList addObject:layout];
  516. // }
  517. // 指定转码流中的每一路输入音频的信息
  518. config.audioMixUserList = [userList copy];
  519. // 指定混合画面的中每一路视频画面的位置、大小、图层以及流类型等信息
  520. config.videoLayoutList = [layoutList copy];
  521. #warning 暂时注释,后续确认是否需要
  522. // 开始发布媒体流 不转码
  523. // [self.trtcCloud startPublishMediaStream:target encoderParam:nil mixingConfig:nil];
  524. // 开始发布媒体流 转码
  525. // [self.trtcCloud startPublishMediaStream:target encoderParam:encoderParam mixingConfig:nil];
  526. // 开始发布媒体流 转码+混流
  527. // [self.trtcCloud startPublishMediaStream:target encoderParam:encoderParam mixingConfig:config];
  528. }
  529. -(void)updateLianMaiCoin
  530. {
  531. //用户加入
  532. NSMutableDictionary *parmDict = [NSMutableDictionary dictionary];
  533. [parmDict setObject:@"live_multi_room" forKey:@"ctl"];
  534. [parmDict setObject:@"api_mic_list" forKey:@"act"];
  535. [parmDict setObject:[BogoNetwork shareInstance].token forKey:@"token"];
  536. [parmDict setObject:[BogoNetwork shareInstance].uid forKey:@"uid"];
  537. [parmDict setObject:self.roomIDStr forKey:@"video_id"];
  538. [[NetHttpsManager manager] POSTWithParameters:parmDict SuccessBlock:^(NSDictionary *responseJson)
  539. {
  540. FWWeakify(self)
  541. if ([responseJson toInt:@"status"] == 1)
  542. {
  543. NSMutableArray *model_arr = [NSMutableArray array];
  544. NSArray *arr = [responseJson valueForKey:@"list"];
  545. if ([arr isKindOfClass:[NSArray class]]) {
  546. for (NSDictionary *dic in arr) {
  547. VoiceLianmaiUserModel *model =[VoiceLianmaiUserModel mj_objectWithKeyValues: dic];
  548. if(model.user_id.intValue == [BogoNetwork shareInstance].uid.intValue)
  549. {
  550. continue;
  551. }
  552. if(model.user_id.intValue == userView1.uid.intValue)
  553. {
  554. userView1.numberLab.text = model.coin;
  555. }
  556. if(model.user_id.intValue == userView2.uid.intValue)
  557. {
  558. userView2.numberLab.text = model.coin;
  559. }
  560. if(model.user_id.intValue == userView2.uid.intValue)
  561. {
  562. userView3.numberLab.text = model.coin;
  563. }
  564. }
  565. }
  566. }
  567. } FailureBlock:^(NSError *error)
  568. {
  569. }];
  570. }
  571. -(void)updateUser
  572. {
  573. //用户加入
  574. NSMutableDictionary *parmDict = [NSMutableDictionary dictionary];
  575. [parmDict setObject:@"live_multi_room" forKey:@"ctl"];
  576. [parmDict setObject:@"api_mic_list" forKey:@"act"];
  577. [parmDict setObject:[BogoNetwork shareInstance].token forKey:@"token"];
  578. [parmDict setObject:[BogoNetwork shareInstance].uid forKey:@"uid"];
  579. [parmDict setObject:self.roomIDStr forKey:@"video_id"];
  580. [[NetHttpsManager manager] POSTWithParameters:parmDict SuccessBlock:^(NSDictionary *responseJson)
  581. {
  582. FWWeakify(self)
  583. if ([responseJson toInt:@"status"] == 1)
  584. {
  585. NSMutableArray *model_arr = [NSMutableArray array];
  586. NSArray *arr = [responseJson valueForKey:@"list"];
  587. if ([arr isKindOfClass:[NSArray class]]) {
  588. for (NSDictionary *dic in arr) {
  589. VoiceLianmaiUserModel *model =[VoiceLianmaiUserModel mj_objectWithKeyValues: dic];
  590. if(model.user_id.intValue == [BogoNetwork shareInstance].uid.intValue)
  591. {
  592. continue;
  593. }
  594. [model_arr addObject:model];
  595. }
  596. }
  597. [self adjustPlayItemVoiceUserList:model_arr];
  598. [self updateLianMaiCoin];
  599. }
  600. } FailureBlock:^(NSError *error)
  601. {
  602. }];
  603. }
  604. //===
  605. #pragma mark 初始化配置
  606. - (void)initConfig
  607. {
  608. [self.view setBackgroundColor:kBlackColor];
  609. [self initializeAgoraEngine];
  610. [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(onPKViewChange:) name:@"onPKViewChange" object:nil];
  611. // 初始化视频父视图
  612. _preViewContainer = [[UIView alloc] initWithFrame:self.view.bounds];
  613. [self.view insertSubview:_preViewContainer atIndex:0];
  614. _preViewContainer.center = self.view.center;
  615. _preViewContainer.backgroundColor = kBlackColor;
  616. int userViewWidth = 120;
  617. int userViewHeight = userViewWidth * 1.6;
  618. userListView = [[UIView alloc] initWithFrame:CGRectMake(kScreenW - userViewWidth - 10, kScreenH - userViewHeight*3 - 60, 0, 0)];
  619. userListView.backgroundColor = kClearColor;
  620. // [self.view addSubview:userListView];
  621. [[GlobalVariables sharedInstance].tliveView addSubview:userListView];
  622. userView1 = [UserView getView];
  623. userView1.delegate = self;
  624. userView1.frame = CGRectMake(0, 0, userViewWidth, userViewHeight);
  625. // userView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, userViewWidth, userViewHeight)];
  626. userView1.backgroundColor = kRedColor;
  627. [userListView addSubview:userView1];
  628. userView2 = [UserView getView];
  629. userView2.delegate = self;
  630. userView2.frame = CGRectMake(0, 0, userViewWidth, userViewHeight);
  631. userView2.backgroundColor = kYellowColor;
  632. [userListView addSubview:userView2];
  633. userView3 = [UserView getView];
  634. userView3.delegate = self;
  635. userView3.frame = CGRectMake(0, 0, userViewWidth, userViewHeight);
  636. userView1.hidden = YES;
  637. userView2.hidden = YES;
  638. userView3.hidden = YES;
  639. userView1.userInteractionEnabled = YES;
  640. userView2.userInteractionEnabled = YES;
  641. userView3.userInteractionEnabled = YES;
  642. //添加手势
  643. UITapGestureRecognizer * tapGesture1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGestureRecognizer:)];
  644. [userView1 addGestureRecognizer:tapGesture1];
  645. //添加手势
  646. UITapGestureRecognizer * tapGesture2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGestureRecognizer:)];
  647. [userView2 addGestureRecognizer:tapGesture2];
  648. UITapGestureRecognizer * tapGesture3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGestureRecognizer:)];
  649. [userView3 addGestureRecognizer:tapGesture3];
  650. [self reloduserListView];
  651. // [userListView alignSubviewsVerticallyWithPadding:0 margin:0];
  652. // [userListView gridViews:userListView.subviews inColumn:1 size:CGSizeMake(userViewWidth, userViewHeight) margin:CGSizeMake(0, 0) inRect:CGRectMake(0, 0, userViewWidth, userViewHeight)];
  653. if (_delegate && [_delegate respondsToSelector:@selector(firstIFrame:)])
  654. {
  655. [_delegate firstIFrame:self];
  656. _rePublishTime = 0;
  657. }
  658. #if TARGET_IPHONE_SIMULATOR
  659. [self toastTip:ASLocalizedString(@"iOS模拟器不支持推流和播放,请使用真机体验")];
  660. #endif
  661. NSLog(ASLocalizedString(@"==========腾讯SDK版本号:%@"),[TXLiveBase getSDKVersionStr]);
  662. }
  663. - (void)handleTapGestureRecognizer:(UITapGestureRecognizer *)gestureRecognizer {
  664. UserView *view = (UserView*)gestureRecognizer.view;
  665. NSString *uid = view.uid;
  666. NSLog(@"点击 %@",uid);
  667. // if([uid isEqualToString:[IMAPlatform sharedInstance].host.userId])
  668. // {
  669. FDActionSheet *actionSheet = [[FDActionSheet alloc] initWithTitle:@"" message:@""];
  670. [actionSheet addAction:[FDAction actionWithTitle:ASLocalizedString(@"下麦") type:FDActionTypeDefault CallBack:^{
  671. NSMutableDictionary *mDict = [NSMutableDictionary dictionary];
  672. [mDict setObject:@"video" forKey:@"ctl"];
  673. [mDict setObject:@"stop_lianmai" forKey:@"act"];
  674. [mDict setObject:self.roomIDStr forKey:@"room_id"];
  675. [mDict setObject:uid forKey:@"to_user_id"];
  676. [[NetHttpsManager manager] POSTWithParameters:mDict SuccessBlock:^(NSDictionary *responseJson) {
  677. } FailureBlock:^(NSError *error) {
  678. }];
  679. }]];
  680. [actionSheet addAction:[FDAction actionWithTitle:ASLocalizedString(@"关闭麦克风") type:FDActionTypeDefault CallBack:^{
  681. // _lianmaiOpenSound = NO;
  682. NSMutableDictionary *mDict = [NSMutableDictionary dictionary];
  683. [mDict setObject:@"video" forKey:@"ctl"];
  684. [mDict setObject:@"setLinkUserMuteVoiceStatus" forKey:@"act"];
  685. [mDict setObject:self.roomIDStr forKey:@"video_id"];
  686. [mDict setObject:@"1" forKey:@"mute_status"];
  687. [[NetHttpsManager manager] POSTWithParameters:mDict SuccessBlock:^(NSDictionary *responseJson) {
  688. NSDictionary * userInfo = [NSDictionary dictionaryWithObject:uid forKey:@"uid"];
  689. [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFY_onMuteUser" object:userInfo userInfo:userInfo];
  690. } FailureBlock:^(NSError *error) {
  691. }];
  692. //view.micbutton.selected NO
  693. // [self.agoraKit enableLocalAudio:view.micbutton.selected];
  694. // view.micbutton.selected = !view.micbutton.selected;
  695. }]];
  696. [actionSheet addAction:[FDAction actionWithTitle:ASLocalizedString(@"取消") type:FDActionTypeCancel CallBack:^{
  697. }]];
  698. [actionSheet show:[UIApplication sharedApplication].keyWindow];
  699. // }
  700. }
  701. -(void)stopLinkMicWithUid:(NSString *)uid
  702. {
  703. }
  704. -(void)reloduserListView
  705. {
  706. //不要动之前的混流逻辑
  707. //删除之前已有的
  708. for (NSString *item in linkedUsers) {
  709. #warning 暂时注释,后续确认是否需要 AgoraPushUtils
  710. // [self.transcoding removeUser:item.intValue];
  711. }
  712. //添加所有
  713. for (int i=0; i<lianMaiuser.count; i++) {
  714. #warning 暂时注释,后续确认是否需要 AgoraPushUtils
  715. // [AgoraPushUtils setLianMaiTranscodingUser:self.transcoding nowNum:i+1 uid:lianMaiuser[i]];
  716. }
  717. // [self.agoraKit updateRtmpTranscoding:self.pushUrlStr transcoding:self.transcoding];
  718. linkedUsers = lianMaiuser;
  719. //延迟两秒更新旁路流
  720. // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  721. // });
  722. }
  723. - (void)initRightVideoContainerView{
  724. if (!_rightVideoContrainerView) {
  725. _rightVideoContrainerView = [[UIView alloc]initWithFrame:CGRectMake(kScreenW / 2, kStatusBarHeight + 53 + 55, kScreenW / 2, kScreenW * 2 / 3)];
  726. _rightVideoContrainerView.backgroundColor = kClearColor;
  727. [self.view addSubview:_rightVideoContrainerView];
  728. }
  729. }
  730. - (void)initTXLivePlayerWithUrl:(NSString *)playUrl playType:(NSInteger)playType{
  731. if([GlobalVariables sharedInstance].openAgora)
  732. {
  733. return;
  734. }
  735. if (!_txLivePlayer) {
  736. _txLivePlayer = [[TXLivePlayer alloc] init];//初始化
  737. }
  738. if (!_txLivePlayConfig) {
  739. _txLivePlayConfig = [[TXLivePlayConfig alloc]init];
  740. _txLivePlayConfig.enableAEC = YES;
  741. }
  742. [_txLivePlayer setConfig:_txLivePlayConfig];
  743. _txLivePlayer.delegate = self; //如果您需要处理播放的事件
  744. [_txLivePlayer setupVideoWidget:CGRectMake(0, 0, 0, 0) containView:_rightVideoContrainerView insertIndex:0];
  745. //4-16 2.苹果连麦无法与安卓和苹果之间连麦,对方是没有影子。
  746. int result = [_txLivePlayer startLivePlay:[NSString stringWithFormat:@"%@%@",playUrl,@""] type:playType];
  747. if (result == -1)
  748. {
  749. [self toastTip:ASLocalizedString(@"非腾讯云链接,若要放开限制请联系腾讯云商务团队")];
  750. }
  751. if( result != 0)
  752. {
  753. NSLog(ASLocalizedString(@"播放器启动失败"));
  754. }
  755. }
  756. #pragma mark - Pk
  757. //该参数就是发送过来的通知,接到通知后执行的方法
  758. - (void)onPKViewChange:(NSNotification *)notify
  759. {
  760. NSLog(@"pk通知来了 = %@",notify);
  761. int isFull = [[notify.userInfo valueForKey:@"isFull"] intValue];
  762. NSString *playUrl = [notify.userInfo valueForKey:@"playUrl"];
  763. TX_Enum_PlayType _playType = PLAY_TYPE_LIVE_RTMP;
  764. if ([playUrl hasPrefix:@"rtmp:"])
  765. {
  766. _playType = PLAY_TYPE_LIVE_RTMP;
  767. }
  768. else if (([playUrl hasPrefix:@"https:"] || [playUrl hasPrefix:@"http:"]) && [playUrl rangeOfString:@".flv"].length > 0)
  769. {
  770. _playType = PLAY_TYPE_LIVE_FLV;
  771. }
  772. if(isFull == 1) {
  773. // self.pkTranscodin = nil;
  774. // [self.agoraKit stopChannelMediaRelay];
  775. //好像有问题,上面代码注释会崩溃
  776. [self.trtcCloud disconnectOtherRoom];
  777. //模拟动态修改
  778. _preViewContainer.frame = self.view.bounds;
  779. // [redBgView removeFromSuperview];
  780. // [blueBgView removeFromSuperview];
  781. [pkBgView removeFromSuperview];
  782. _txLivePlayer.delegate = nil;
  783. [_txLivePlayer stopPlay];
  784. [_txLivePlayer removeVideoWidget];
  785. _txLivePlayer = nil;
  786. [_rightVideoContrainerView removeFromSuperview];
  787. _rightVideoContrainerView = nil;
  788. float width = 34;
  789. float height = 34;
  790. float offsetX = (self.view.frame.size.width - width) / 2;
  791. float offsetY = (self.view.frame.size.height - height) / 2;
  792. _loadingImageView.frame = CGRectMake(offsetX, offsetY, width, height);
  793. [_txLivePublisher setVideoQuality:VIDEO_QUALITY_HIGH_DEFINITION adjustBitrate:YES adjustResolution:YES];
  794. _isMix = NO;
  795. [self stopLoadingAnimation];
  796. return;
  797. }
  798. if(isFull == 3) {
  799. // _preViewContainer.frame = CGRectMake(0, 0, kScreenW/2, kScreenH/);
  800. _preViewContainer.frame = CGRectMake(0, kStatusBarHeight + 53 + 55, kScreenW / 2, kScreenW * 2 / 3);
  801. [self addPkBgView];
  802. [self initRightVideoContainerView];
  803. [self initTXLivePlayerWithUrl:[self changeRTMPToFlv:playUrl] playType:_playType];
  804. _loadingImageView.centerX = _rightVideoContrainerView.centerX;
  805. _loadingImageView.centerY = _rightVideoContrainerView.centerY;
  806. [_txLivePublisher setVideoQuality:VIDEO_QUALITY_STANDARD_DEFINITION adjustBitrate:YES adjustResolution:YES];
  807. if([GlobalVariables sharedInstance].openAgora)
  808. {
  809. NSMutableDictionary *mDict = [NSMutableDictionary dictionary];
  810. [mDict setObject:@"pk_agora" forKey:@"ctl"];
  811. BogoPkProgressModel *model = [notify.userInfo valueForKey:@"model"];
  812. [mDict setObject:@"getPKRTCChannelToken" forKey:@"act"];
  813. [mDict setObject:[NSString stringWithFormat:@"%@",model.id] forKey:@"pk_id"];
  814. [[NetHttpsManager manager] POSTWithParameters:mDict SuccessBlock:^(NSDictionary *responseJson) {
  815. if ([responseJson toInt:@"status"] == 1 || [responseJson toInt:@"status"] == 2) {
  816. //imUserId 是主播自己的id
  817. NSInteger imUserId = [IMAPlatform sharedInstance].host.imUserId.integerValue;
  818. //src_token 是别人要加入我房间的源token
  819. NSString *src_token = responseJson[@"data"][@"agora_token_src"];
  820. //desc_token 是要加入对方房间的token
  821. NSString *desc_token = responseJson[@"data"][@"agora_token_desc"];
  822. #warning 暂时注释,后续确认是否需要
  823. /*
  824. //总体的config
  825. AgoraChannelMediaRelayConfiguration *config = [[AgoraChannelMediaRelayConfiguration alloc] init];
  826. config.sourceInfo = [[AgoraChannelMediaRelayInfo alloc] initWithToken:responseJson[@"data"][@"agora_token_src"]];
  827. config.sourceInfo.uid = 0;
  828. //声明一个sourceInfo ,用我的房间token
  829. config.sourceInfo = [[AgoraChannelMediaRelayInfo alloc] initWithToken:src_token];
  830. //文档说了必须设置成0
  831. // config.sourceInfo.uid = imUserId;
  832. */
  833. //tagget 是对方的roomid,也是频道号
  834. NSString *tagget = @"";
  835. //myromid 是我的房间号也是我的频道id
  836. NSString *myRoomId = @"";
  837. //toEmccUserid 对方主播的id
  838. NSString *toEmccUserid = @"";
  839. NSString *pushUrl;
  840. if(model.emcee_user_id1.intValue == imUserId) {
  841. tagget = model.room_id2;
  842. myRoomId = model.room_id1;
  843. toEmccUserid = model.emcee_user_id2;
  844. pushUrl = model.push_url1;
  845. } else {
  846. toEmccUserid = model.emcee_user_id1;
  847. tagget = model.room_id1;
  848. myRoomId = model.room_id2;
  849. pushUrl = model.push_url2;
  850. }
  851. //开始混流
  852. // int status = [self.agoraKit startChannelMediaRelay:config];
  853. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  854. // 需要延迟执行的代码
  855. // [self channelMediaRelayWidthUid:imUserId andSrcToken:src_token andDestToken:desc_token andChannel:tagget];
  856. });
  857. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  858. // 需要延迟执行的代码
  859. // AgoraRtcVideoCanvas *videoCanvas = [[AgoraRtcVideoCanvas alloc] init];
  860. // videoCanvas.uid = toEmccUserid.intValue;
  861. // videoCanvas.renderMode = AgoraVideoRenderModeHidden;
  862. // videoCanvas.view = self->_rightVideoContrainerView;
  863. // // 设置远端视图
  864. // [self.agoraKit setupRemoteVideo:videoCanvas];
  865. // 功能描述:请求跨房通话
  866. NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];
  867. // 此处为数字房间号; 数字房间号为 roomId 对方房间ID,对方主播ID
  868. [jsonDict setObject:@(tagget.intValue) forKey:@"roomId"];
  869. [jsonDict setObject:toEmccUserid forKey:@"userId"];
  870. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:nil];
  871. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  872. [self.trtcCloud connectOtherRoom:jsonString];
  873. TRTCRenderParams *params = [[TRTCRenderParams alloc] init];
  874. // 画面镜像模式
  875. params.mirrorType = TRTCVideoMirrorTypeDisable;
  876. // 画面填充模式
  877. params.fillMode = TRTCVideoFillMode_Fill;
  878. // 画面旋转角度
  879. params.rotation = TRTCVideoRotation_0;
  880. // 设置远端画面的渲染模式
  881. [self.trtcCloud setRemoteRenderParams:toEmccUserid streamType:TRTCVideoStreamTypeBig params:params];
  882. [self.trtcCloud startRemoteView:toEmccUserid streamType:TRTCVideoStreamTypeBig view:self->_rightVideoContrainerView];
  883. });
  884. // [self setPKTranscodingWithId:toEmccUserid];
  885. // NSLog(@"status %d",status);
  886. }
  887. } FailureBlock:^(NSError *error) {
  888. //do nothing;
  889. }];
  890. //跨频道推流
  891. }
  892. return;
  893. }
  894. if(isFull == 0)
  895. {
  896. _preViewContainer.frame = CGRectMake(0, kStatusBarHeight + 53 + 55, kScreenW / 2, kScreenW * 2 / 3);
  897. // _preViewContainer.frame = CGRectMake(kScreenW/2, 0, kScreenW/2, kScreenH/2);
  898. [self addPkBgView];
  899. [self initRightVideoContainerView];
  900. [self initTXLivePlayerWithUrl:[self changeRTMPToFlv:playUrl] playType:_playType];
  901. _loadingImageView.centerX = _rightVideoContrainerView.centerX;
  902. _loadingImageView.centerY = _rightVideoContrainerView.centerY;
  903. [_txLivePublisher setVideoQuality:VIDEO_QUALITY_STANDARD_DEFINITION adjustBitrate:YES adjustResolution:YES];
  904. return;
  905. }
  906. }
  907. -(void)channelMediaRelayWidthUid:(int)uid andSrcToken:(NSString *)srcToken andDestToken:(NSString *)destToken andChannel:(NSString *)channel;
  908. {
  909. //如果不是主播直接退出
  910. // AgoraChannelMediaRelayConfiguration *config = [[AgoraChannelMediaRelayConfiguration alloc] init];
  911. // AgoraChannelMediaRelayInfo *src = [config sourceInfo];
  912. //
  913. //// src.channelName = nil;
  914. // src.uid = 0;
  915. // src.token = srcToken;
  916. //
  917. //
  918. // AgoraChannelMediaRelayInfo *dst = [[AgoraChannelMediaRelayInfo alloc] init];
  919. // dst.channelName = channel;
  920. // dst.uid = uid;
  921. // dst.token = destToken;
  922. //
  923. // [config setDestinationInfo:dst forChannelName:dst.channelName];
  924. if(_isMix == NO)
  925. {
  926. _isMix = YES;
  927. // [self.agoraKit stopChannelMediaRelay];
  928. //功能描述:退出跨房通话
  929. [self.trtcCloud disconnectOtherRoom];
  930. // [self.agoraKit startChannelMediaRelay:config];
  931. // 功能描述:请求跨房通话
  932. NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];
  933. // 此处为字符房间号; 数字房间号为 roomId
  934. [jsonDict setObject:channel forKey:@"roomId"];
  935. [jsonDict setObject:@(uid) forKey:@"userId"];
  936. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:nil];
  937. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  938. [self.trtcCloud connectOtherRoom:jsonString];
  939. }
  940. }
  941. - (void)addVSView{
  942. //红蓝双方
  943. if (!redBgView) {
  944. redBgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW / 2, kScreenH)];
  945. redBgView.backgroundColor = [UIColor colorWithHexString:@"#731a5a"];
  946. [self.view addSubview:redBgView];
  947. [self.view sendSubviewToBack:redBgView];
  948. }else{
  949. [self.view addSubview:redBgView];
  950. [self.view sendSubviewToBack:redBgView];
  951. }
  952. if (!blueBgView) {
  953. blueBgView = [[UIView alloc]initWithFrame:CGRectMake(kScreenW / 2, 0, kScreenW / 2, kScreenH)];
  954. blueBgView.backgroundColor = [UIColor colorWithHexString:@"#012e89"];
  955. [self.view addSubview:blueBgView];
  956. [self.view sendSubviewToBack:blueBgView];
  957. }else{
  958. [self.view addSubview:blueBgView];
  959. [self.view sendSubviewToBack:blueBgView];
  960. }
  961. }
  962. - (void)addPkBgView{
  963. if (!pkBgView) {
  964. pkBgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
  965. pkBgView.image = [UIImage imageNamed:@"pk_bg"];
  966. }
  967. [self.view addSubview:pkBgView];
  968. [self.view sendSubviewToBack:pkBgView];
  969. }
  970. - (void)viewWillDisappear:(BOOL)animated {
  971. [super viewWillDisappear:animated];
  972. if (!self.txLivePublisher.isPublishing) {
  973. [[NSNotificationCenter defaultCenter]removeObserver:self name:@"onPKViewChange" object:nil];
  974. [GlobalVariables sharedInstance].appModel.spear_live = @"0";
  975. // if (self.tiSDKManager) {
  976. // [self.tiSDKManager destroy];
  977. // self.tiSDKManager = nil;
  978. // if(_tiUIView.viewArr != nil)
  979. // for (UIView *sview in _tiUIView.viewArr) {
  980. // [sview removeFromSuperview];
  981. // }
  982. // }
  983. }
  984. }
  985. //6-19 修改-onPKViewChange
  986. -(void)viewWillAppear:(BOOL)animated{
  987. [super viewWillAppear:animated];
  988. // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPKViewChange:) name:@"onPKViewChange" object:nil];
  989. }
  990. - (void)viewDidDisappear:(BOOL)animated{
  991. [super viewDidDisappear:animated];
  992. }
  993. - (void)viewDidAppear:(BOOL)animated
  994. {
  995. [super viewDidAppear:animated];
  996. #if !TARGET_IPHONE_SIMULATOR
  997. //是否有摄像头权限
  998. AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  999. if (statusVideo == AVAuthorizationStatusDenied)
  1000. {
  1001. [FanweMessage alert:ASLocalizedString(@"获取摄像头权限失败,请前往隐私-相机设置里面打开应用权限")];
  1002. return;
  1003. }
  1004. #endif
  1005. }
  1006. #pragma mark - ----------------------- 开始、停止推流 -----------------------
  1007. #pragma mark 开始推流
  1008. - (BOOL)startPushRtmpLiveMethod {
  1009. _startTime = [[NSDate date]timeIntervalSince1970]*1000;
  1010. _lastTime = _startTime;
  1011. NSString* rtmpUrl = self.pushUrlStr;
  1012. [self joinChannel];
  1013. //是否有摄像头权限
  1014. AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  1015. if (statusVideo == AVAuthorizationStatusDenied)
  1016. {
  1017. [FanweMessage alert:ASLocalizedString(@"获取摄像头权限失败,请前往隐私-相机设置里面打开应用权限")];
  1018. return NO;
  1019. }
  1020. //是否有麦克风权限
  1021. AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
  1022. if (statusAudio == AVAuthorizationStatusDenied)
  1023. {
  1024. [FanweMessage alert:ASLocalizedString(@"获取麦克风权限失败,请前往隐私-麦克风设置里面打开应用权限")];
  1025. return NO;
  1026. }
  1027. return YES;
  1028. }
  1029. #pragma mark 停止推流
  1030. - (void)stopRtmp {
  1031. if (_txLivePlayer != nil) {
  1032. _txLivePlayer.delegate = nil;
  1033. [_txLivePlayer stopPlay];
  1034. [_txLivePlayer removeVideoWidget];
  1035. }
  1036. }
  1037. #pragma mark - BeautySettingPanelDelegate
  1038. - (void)onSetBeautyStyle:(NSUInteger)beautyStyle beautyLevel:(float)beautyLevel whitenessLevel:(float)whitenessLevel ruddinessLevel:(float)ruddinessLevel {
  1039. [_txLivePublisher setBeautyStyle:beautyStyle beautyLevel:beautyLevel whitenessLevel:whitenessLevel ruddinessLevel:ruddinessLevel];
  1040. }
  1041. - (void)onSetMixLevel:(float)mixLevel {
  1042. [_txLivePublisher setSpecialRatio:mixLevel / 10.0];
  1043. }
  1044. - (void)onSetEyeScaleLevel:(float)eyeScaleLevel {
  1045. [_txLivePublisher setEyeScaleLevel:eyeScaleLevel];
  1046. }
  1047. - (void)onSetFaceScaleLevel:(float)faceScaleLevel {
  1048. [_txLivePublisher setFaceScaleLevel:faceScaleLevel];
  1049. }
  1050. - (void)onSetFaceBeautyLevel:(float)beautyLevel {
  1051. }
  1052. - (void)onSetFaceVLevel:(float)vLevel {
  1053. [_txLivePublisher setFaceVLevel:vLevel];
  1054. }
  1055. - (void)onSetChinLevel:(float)chinLevel {
  1056. [_txLivePublisher setChinLevel:chinLevel];
  1057. }
  1058. - (void)onSetFaceShortLevel:(float)shortLevel {
  1059. [_txLivePublisher setFaceShortLevel:shortLevel];
  1060. }
  1061. - (void)onSetNoseSlimLevel:(float)slimLevel {
  1062. [_txLivePublisher setNoseSlimLevel:slimLevel];
  1063. }
  1064. - (void)onSetFilter:(UIImage*)filterImage {
  1065. [_txLivePublisher setFilter:filterImage];
  1066. }
  1067. - (void)onSetGreenScreenFile:(NSURL *)file {
  1068. [_txLivePublisher setGreenScreenFile:file];
  1069. }
  1070. - (void)onSelectMotionTmpl:(NSString *)tmplName inDir:(NSString *)tmplDir {
  1071. [_txLivePublisher selectMotionTmpl:tmplName inDir:tmplDir];
  1072. }
  1073. #pragma mark ------------TXLivePlayListener----------
  1074. -(void) onPlayEvent:(int)EvtID withParam:(NSDictionary*)param{
  1075. switch (EvtID) {
  1076. case PLAY_EVT_PLAY_BEGIN:
  1077. [self stopLoadingAnimation];
  1078. break;
  1079. case PLAY_EVT_PLAY_LOADING:
  1080. [self startLoadingAnimation];
  1081. break;
  1082. default:
  1083. break;
  1084. }
  1085. }
  1086. - (void)startLoadingAnimation
  1087. {
  1088. if (_loadingImageView != nil)
  1089. {
  1090. _loadingImageView.hidden = NO;
  1091. [_loadingImageView startAnimating];
  1092. }
  1093. }
  1094. - (void)stopLoadingAnimation
  1095. {
  1096. if (_loadingImageView != nil)
  1097. {
  1098. _loadingImageView.hidden = YES;
  1099. [_loadingImageView stopAnimating];
  1100. }
  1101. }
  1102. #pragma mark - ----------------------- 摄像头、闪光灯 -----------------------
  1103. #pragma mark 开、关闪光灯
  1104. - (void)clickTorch:(BOOL)isOpen
  1105. {
  1106. if (_txLivePublisher)
  1107. {
  1108. if (![_txLivePublisher toggleTorch:isOpen])
  1109. {
  1110. [self toastTip:ASLocalizedString(@"闪光灯启动失败")];
  1111. }
  1112. }
  1113. }
  1114. #pragma mark 前置后置摄像头切换
  1115. - (void)clickCamera:(UIButton*)btn
  1116. {
  1117. [_txLivePublisher switchCamera];
  1118. }
  1119. #pragma mark - ----------------------- 定义清晰度 -----------------------
  1120. - (void)changeHD:(UIButton*)btn
  1121. {
  1122. if ([btn.titleLabel.text isEqualToString:@"720p"] && NO == [self isSuitableMachine:7])
  1123. {
  1124. [FanweMessage alert:ASLocalizedString(@"直播推流")message:ASLocalizedString(@"iphone 6 及以上机型适合开启720p!")isHideTitle:NO destructiveAction:nil];
  1125. return;
  1126. }
  1127. if ([btn.titleLabel.text isEqualToString:@"540p"] && NO == [self isSuitableMachine:5])
  1128. {
  1129. [FanweMessage alert:ASLocalizedString(@"直播推流")message:ASLocalizedString(@"iphone 5 及以上机型适合开启540p!")isHideTitle:NO destructiveAction:nil];
  1130. return;
  1131. }
  1132. if (_txLivePublisher == nil) return;
  1133. if ([btn.titleLabel.text isEqualToString:@"720p"])
  1134. {
  1135. TXLivePushConfig* _config = _txLivePublisher.config;
  1136. _config.videoBitratePIN = 1500;
  1137. _config.videoResolution = [self isSuitableMachine:7 ] ? VIDEO_RESOLUTION_TYPE_720_1280 : VIDEO_RESOLUTION_TYPE_540_960;
  1138. _config.enableAutoBitrate = NO;
  1139. [_txLivePublisher setConfig:_config];
  1140. }
  1141. else if ([btn.titleLabel.text isEqualToString:@"540p"])
  1142. {
  1143. TXLivePushConfig* _config = _txLivePublisher.config;
  1144. _config.videoBitratePIN = 1000;
  1145. _config.videoResolution = [self isSuitableMachine:5 ] ? VIDEO_RESOLUTION_TYPE_540_960 : VIDEO_RESOLUTION_TYPE_360_640;
  1146. _config.enableAutoBitrate = NO;
  1147. [_txLivePublisher setConfig:_config];
  1148. }
  1149. else if ([btn.titleLabel.text isEqualToString:@"360p"])
  1150. {
  1151. TXLivePushConfig* _config = _txLivePublisher.config;
  1152. _config.videoBitratePIN = 700;
  1153. _config.videoResolution = VIDEO_RESOLUTION_TYPE_360_640;
  1154. _config.enableAutoBitrate = NO;
  1155. [_txLivePublisher setConfig:_config];
  1156. }
  1157. else if ([btn.titleLabel.text isEqualToString:@"360+"])
  1158. {
  1159. TXLivePushConfig* _config = _txLivePublisher.config;
  1160. _config.videoBitrateMin = 500;
  1161. _config.videoBitrateMax = 1200;
  1162. _config.enableAutoBitrate = YES;
  1163. _config.videoResolution = VIDEO_RESOLUTION_TYPE_360_640;
  1164. [_txLivePublisher setConfig:_config]; // 此模式下设置bitrate无效
  1165. }
  1166. }
  1167. // iphone 6 及以上机型适合开启720p, 否则20帧的帧率可能无法达到, 这种"流畅不足,清晰有余"的效果并不好
  1168. - (BOOL)isSuitableMachine:(int)targetPlatNum
  1169. {
  1170. int mib[2] = {CTL_HW, HW_MACHINE};
  1171. size_t len = 0;
  1172. char* machine;
  1173. sysctl(mib, 2, NULL, &len, NULL, 0);
  1174. machine = (char*)malloc(len);
  1175. sysctl(mib, 2, machine, &len, NULL, 0);
  1176. NSString* platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
  1177. free(machine);
  1178. if ([platform length] > 6)
  1179. {
  1180. NSString * platNum = [NSString stringWithFormat:@"%C", [platform characterAtIndex: 6 ]];
  1181. return ([platNum intValue] >= targetPlatNum);
  1182. }
  1183. else
  1184. {
  1185. return NO;
  1186. }
  1187. }
  1188. #pragma mark - ----------------------- 自定义Toast -----------------------
  1189. /**
  1190. @method 获取指定宽度width的字符串在UITextView上的高度
  1191. @param textView 待计算的UITextView
  1192. @param Width 限制字符串显示区域的宽度
  1193. @result float 返回的高度
  1194. */
  1195. - (float)heightForString:(UITextView *)textView andWidth:(float)width
  1196. {
  1197. CGSize sizeToFit = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
  1198. return sizeToFit.height;
  1199. }
  1200. - (void)toastTip:(NSString*)toastInfo
  1201. {
  1202. NSLog(@"======publishtoastInfo:%@",toastInfo);
  1203. CGRect frameRC = [[UIScreen mainScreen] bounds];
  1204. frameRC.origin.y = frameRC.size.height - 110;
  1205. frameRC.size.height -= 110;
  1206. __block UITextView * toastView = [[UITextView alloc] init];
  1207. toastView.editable = NO;
  1208. toastView.selectable = NO;
  1209. frameRC.size.height = [self heightForString:toastView andWidth:frameRC.size.width];
  1210. toastView.frame = frameRC;
  1211. toastView.text = toastInfo;
  1212. toastView.backgroundColor = [UIColor whiteColor];
  1213. toastView.alpha = 0.5;
  1214. [self.view addSubview:toastView];
  1215. dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);
  1216. dispatch_after(popTime, dispatch_get_main_queue(), ^(){
  1217. [toastView removeFromSuperview];
  1218. toastView = nil;
  1219. });
  1220. }
  1221. #pragma mark ---------美颜增加-------------
  1222. //隐藏美颜
  1223. /*
  1224. - (GLuint)onPreProcessTexture:(GLuint)texture width:(CGFloat)width height:(CGFloat)height{
  1225. return [[TiSDKManager shareManager] renderTexture2D:texture Width:width Height:height Rotation:CLOCKWISE_0 Mirror:_txLivePublisher.config.frontCamera];
  1226. // if (self.tiSDKManager && [self.tiSDKManager renderTexture2D:texture Width:width Height:height Rotation:CLOCKWISE_0 Mirror:NO]) {
  1227. // /////////////////// TiFaceSDK 添加 开始 ///////////////////
  1228. // return [self.tiSDKManager renderTexture2D:texture Width:width Height:height Rotation:CLOCKWISE_0 Mirror:NO];
  1229. // /////////////////// TiFaceSDK 添加 结束 ///////////////////
  1230. // }
  1231. // return texture;
  1232. }*/
  1233. //#pragma mark ---------美颜增加-------------
  1234. //- (GLuint)onPreProcessTexture:(GLuint)texture width:(CGFloat)width height:(CGFloat)height{
  1235. // if (self.tiSDKManager && [self.tiSDKManager renderTexture2D:texture Width:width Height:height Rotation:CLOCKWISE_0 Mirror:NO]) {
  1236. // /////////////////// TiFaceSDK 添加 开始 ///////////////////
  1237. // return [self.tiSDKManager renderTexture2D:texture Width:width Height:height Rotation:CLOCKWISE_0 Mirror:NO];
  1238. // /////////////////// TiFaceSDK 添加 结束 ///////////////////
  1239. // }
  1240. // return texture;
  1241. //}
  1242. //可以在这里释放创建的OpenGL资源
  1243. - (void)onTextureDestoryed{
  1244. // [self.tiSDKManager destroy];
  1245. }
  1246. - (NSString *)changeRTMPToFlv:(NSString *)originalString{
  1247. NSMutableString *mStr = [NSMutableString stringWithString:originalString];
  1248. // [mStr replaceCharactersInRange:NSMakeRange(0, 4) withString:@"http"];
  1249. // [mStr appendString:@".flv"];
  1250. return mStr;
  1251. }
  1252. //功能描述:音量大小的反馈回调
  1253. //SDK 可以评估每一路音频的音量大小,并每隔一段时间抛出该事件回调,您可以根据音量大小在 UI 上做出相应的提示,比如 波形图 或 音量槽 。 要完成这个功能, 您需要先调用 enableAudioVolumeEvaluation 开启这个能力并设定事件抛出的时间间隔。 需要补充说明的是,无论当前房间中是否有人说话,SDK 都会按照您设定的时间间隔定时抛出此事件回调。
  1254. - (void)onUserVoiceVolume:(NSArray<TRTCVolumeInfo *> *)userVolumes totalVolume:(NSInteger)totalVolume {
  1255. //totalVolume
  1256. NSLog(@"totalVolume");
  1257. NSLog(@"%ld",totalVolume);
  1258. /*bug:当a用户在麦上正在说话时,切换到无网状态,此时虽然还显示在麦上(im还没下线),
  1259. 但观众席听不到声音,光圈还在闪烁
  1260. 原因: 这时观众席speakers 里面找不到a,就不会进入for循环,就不会更新a的声音为0
  1261. 解决: 1先找到 麦上的用户 2去判断有无声音
  1262. */
  1263. for (TRTCVolumeInfo *info in userVolumes) {
  1264. // for (AgoraRtcAudioVolumeInfo *speaker in speakers) {
  1265. NSString *uid = @"";
  1266. if (info.userId.intValue == 0) {
  1267. uid = [IMAPlatform sharedInstance].host.userId;
  1268. }else{
  1269. uid = [NSString stringWithFormat:@"%@",info.userId];
  1270. }
  1271. if([[userView1 uid] isEqualToString:uid])
  1272. {
  1273. userView1.totalVolume = info.volume;
  1274. }
  1275. if([[userView2 uid] isEqualToString:uid])
  1276. {
  1277. userView2.totalVolume = info.volume;
  1278. }
  1279. if([[userView3 uid] isEqualToString:uid])
  1280. {
  1281. userView3.totalVolume = info.volume;
  1282. }
  1283. //speaker.volume
  1284. }
  1285. if(userVolumes.count == 0)
  1286. {
  1287. userView1.totalVolume = 0;
  1288. userView2.totalVolume = 0;
  1289. userView3.totalVolume = 0;
  1290. }
  1291. // [self.uiController.micView setUsers:self.users];
  1292. }
  1293. @end