YH_RootViewController.m
53.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
//
// YH_RootViewController.m
// YohoLive
//
// Created by 盖剑秋 on 16/6/6.
// Copyright © 2016年 YOHO!. All rights reserved.
//
#import "YH_RootViewController.h"
#import "TXLivePush.h"
#import <sys/types.h>
#import <sys/sysctl.h>
#import "TXRTMPAPI.h"
#import "PureLayout.h"
#import "YH_ChannelModel.h"
#import "YH_ChannelCell.h"
#import <AVFoundation/AVFoundation.h>
#import "AFHTTPSessionManager.h"
#import "YH_HTTPRequestSerializer.h"
#import "GCDAsyncSocket+SocketHandler.h"
#import "AFNetworkReachabilityManager.h"
#import "Macros.h"
#import "YH_BarrageViewController.h"
#import "YH_SocketService.h"
#import "UIViewAdditions.h"
#import <CommonCrypto/CommonDigest.h>
//static const NSInteger socketMaxRetryCount = 3;
// 清晰度定义
#define HD_LEVEL_720P 1 // 1280 * 720
#define HD_LEVEL_540P 2 // 960 * 560
#define HD_LEVEL_360P 3 // 640 * 360
#define HD_LEVEL_360_PLUS 4 // 640 * 360 且开启码率自适应
#define RTMP_PUBLISH_URL @"rtmp://2718.livepush.myqcloud.com/live/2718_01973243308211e6a2cba4dcbef5e35a?bizid=2718" //调试期间您可以修改之以避免输入地址的麻烦
#define SOCKET_LIVE_HOST @"123.206.65.220"
#define SOCKET_LIVE_PORT 9512
#define SOCKET_COMMAND @"cmd"
#define kPushging @"pushing_key"
#define END_ACKCMD @"99"
@interface YH_RootViewController ()<TXLivePushListener, UITableViewDelegate, UITableViewDataSource,YH_SocketServiceDelegate,UIAlertViewDelegate>
@property (nonatomic, strong) TXLivePush *livePush;
//buttons
@property (nonatomic, strong) UIButton *torchButton;
@property (nonatomic, strong) UIButton *cameraSwitchButton;
@property (nonatomic, strong) UIButton *fullScreenButton;
@property (nonatomic, strong) UIButton *channelButton;
@property (nonatomic, strong) UIButton *beautyButton;
@property (nonatomic, strong) UIButton *accellerateButton;
@property (nonatomic, strong) UIButton *logButton;
@property (nonatomic, strong) UIButton *hdButton;
@property (nonatomic, strong) UIView *channelPannel;
@property (nonatomic, strong) UIButton *liveButton;//开始直播、结束直播。
@property (nonatomic, strong) NSArray<YH_ChannelModel *> *channels;
@property (nonatomic, strong) YH_ChannelModel *currentChannel;
@property (nonatomic, strong) UITableView *channelTable;
@property (nonatomic, assign) NSInteger currentChannelIndex;
@property (nonatomic, strong) UIView *vBeauty;
@property (nonatomic, strong) UISlider *sdBeauty;
@property (nonatomic, strong) UISlider *sdWhitening;
@property (nonatomic, strong) UIView *vHD;
@property (nonatomic, strong) UIButton *radioBtnHD;
@property (nonatomic, strong) UIButton *radioBtnHD2;
@property (nonatomic, strong) UIButton *radioBtnSD;
@property (nonatomic, strong) UIButton *radioBtnAUTO;
@property (nonatomic, strong) NSString *tipsMsg;
@property (nonatomic, strong) NSString *logMsg;
@property (nonatomic, strong) UITextView *statusView;
@property (nonatomic, strong) UITextView *logViewEvt;
@property (nonatomic, assign) unsigned long long startTime;
@property (nonatomic, assign) unsigned long long lastTime;
@property (nonatomic, strong) UIView *cover;
@property (nonatomic, assign) int beauty_level;
@property (nonatomic, assign) int whitening_level;
@property (nonatomic, strong) UIView *emojiPannel;
@property (nonatomic, strong) UIImageView *emojiImage;
@property (nonatomic, strong) UILabel *emojiCountLabel;
@property (nonatomic, strong) UIView *infoPannel;
@property (nonatomic, strong) UILabel *onlineCountLabel;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, assign) NSInteger totalTime;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) BOOL loading;
@property (nonatomic, strong) GCDAsyncSocket *socket;
@property (nonatomic, assign) NSInteger currentRetryCount;
@property (nonatomic, strong) NSTimer *socketTimer;
@property (nonatomic, assign) BOOL inPushing;//是否正在直播,直播中无法切换房间以及开始新的频道直播。
@property (strong, nonatomic) YH_BarrageViewController *barrageViewController;
@property (strong, nonatomic) YH_SocketService *socketService;
@end
@implementation YH_RootViewController
- (YH_BarrageViewController *) barrageViewController
{
if (_barrageViewController == nil) {
_barrageViewController = [[YH_BarrageViewController alloc]initWithType:YHBarrageTypeReadonly];
}
return _barrageViewController;
}
- (YH_SocketService *)socketService
{
if (_socketService == nil) {
_socketService = [[YH_SocketService alloc]init];
_socketService.delegate = self;
}
return _socketService;
}
- (BOOL)prefersStatusBarHidden
{
return YES;
}
- (void)viewDidLoad {
[super viewDidLoad];
_currentChannelIndex = -1;
self.view.backgroundColor = [UIColor orangeColor];
[self initUI];
[self loadChannelData];
[self setUpPush];
_socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
_currentRetryCount = 0;
}
- (void)continueRTMP {
if (_currentChannel) {
if ([self startRtmp]) {
[self toastTip:@"开始直播"];
_totalTime = _currentChannel.totalTime;
_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateInfoView) userInfo:nil repeats:YES];
[_timer fire];
_liveButton.selected = YES;
[self clearLog];
self.socketService.room = _currentChannel.room;
self.socketService.uid = @"9527";
self.socketService.userName = @"aaaa";
[self.socketService connect];
}
}
}
- (void)setUpPush {
_livePush = [TXLivePush new];
[_livePush setLogLevel:LOGLEVEL_ERROR];
TXLivePushConfig *config = [[TXLivePushConfig alloc] init];
[_livePush setConfig:config];
_livePush.delegate = self;
[_livePush startPreview:self.view];
}
- (void)loadChannelData {
//测试数据。
// YH_ChannelModel *model1 = [YH_ChannelModel new];
// model1.roomTitle = @"啦啦啦啦";
// model1.roomURL = @"rtmp://2718.livepush.myqcloud.com/live/2718_01973243308211e6a2cba4dcbef5e35a?bizid=2718";
// YH_ChannelModel *model2 = [YH_ChannelModel new];
// model2.roomTitle = @"噜噜噜噜";
// model2.roomURL = @"rtmp://2718.livepush.myqcloud.com/live/2718_01973243308211e6a2cba4dcbef5e35a?bizid=2718";
// YH_ChannelModel *model3 = [YH_ChannelModel new];
// model3.roomTitle = @"咯囖囖囖囖";
// model3.roomURL = @"rtmp://2718.livepush.myqcloud.com/live/2718_01973243308211e6a2cba4dcbef5e35a?bizid=2718";
// YH_ChannelModel *model4 = [YH_ChannelModel new];
// model4.roomTitle = @"哩哩哩哩哩";
// model4.roomURL = @"rtmp://2718.livepush.myqcloud.com/live/2718_01973243308211e6a2cba4dcbef5e35a?bizid=2718";
// _channels = @[model1,model2,model3,model4];
// [_channelTable reloadData];
if (_loading) {
return;
}
_loading = YES;
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
NSURLSessionDataTask *task= [manager
GET:@"http://newboys.test.yoho.cn/yohoboyins/v4/qcloud/getPushFlow"
parameters:nil progress:NULL
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if ([responseObject isKindOfClass:[NSDictionary class]]) {
id data = responseObject[@"data"];
if (![data isKindOfClass:[NSArray class]]) {
[self toastTip:@"没有可用直播间"];
return;
}
NSMutableArray *tempAry = @[].mutableCopy;
[data enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (![obj isKindOfClass:[NSDictionary class]]) {
*stop = YES;
[self toastTip:@"没有可用直播间"];
}
YH_ChannelModel *model = [YH_ChannelModel new];
model.roomTitle = obj[@"name"];
model.roomURL = obj[@"url"];
model.channel_id = obj[@"channel_id"];
model.cid = obj[@"cid"];
model.app = obj[@"app"];
model.type = obj[@"type"];
model.room = obj[@"id"];
[tempAry addObject:model];
}];
_channels = [NSArray arrayWithArray:tempAry];
[_channelTable reloadData];
}
NSLog(@"bbbb%@",responseObject);
_loading = NO;
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
_loading = NO;
[self toastTip:[NSString stringWithFormat:@"房间加载失败:%@",error.localizedDescription]];
}];
NSLog(@"%@",task.originalRequest.URL.absoluteString);
}
#pragma mark --sockerserviceDelegate
- (NSString *)formatNumer:(NSString *)number
{
NSInteger num = number.integerValue;
NSInteger a = 0;
NSInteger b = 0;
if (num >9999) {
a = ceilf(num /10000);
b = ceilf((num - a * 10000)/ 1000);
return [NSString stringWithFormat:@"%ld.%ld万",(long)a,(long)b];
}else{
return [NSString stringWithFormat:@"%@",number];
}
}
- (void)userPraised:(NSString *)currentTotalNum isSelfPraise:(BOOL)isSelf
{
self.emojiCountLabel.text =[self formatNumer:currentTotalNum];
}
- (void)currentPeopleNumber:(NSString *)peopleNumber
{
self.onlineCountLabel.text =[NSString stringWithFormat:@"%@人在线",[self formatNumer:peopleNumber]];
}
- (void)livePalyEnd:(NSString *)audienceNums likeNums:(NSString *)likeNums videoLen:(NSString *)videoLen
{
}
- (void)liveOnlineNums:(NSString *)onlineNums likes:(NSString *)likes
{
self.emojiCountLabel.text =[self formatNumer:likes];
self.onlineCountLabel.text =[NSString stringWithFormat:@"%@人在线",[self formatNumer:onlineNums]];
}
#pragma mark - Publisher delegate methods...
- (void)clearLog {
_tipsMsg = @"";
_logMsg = @"";
[_statusView setText:@""];
[_logViewEvt setText:@""];
_startTime = [[NSDate date] timeIntervalSince1970]*1000;
_lastTime = _startTime;
}
- (void)updateInfoView {
_totalTime ++;
long hours = _totalTime/3600;
long seconds = _totalTime%60;
long minutes = (_totalTime/60)%60;
NSString *hourStr = hours<10?[NSString stringWithFormat:@"0%ld",hours]:[NSString stringWithFormat:@"%ld",hours];
NSString *secondStr = seconds<10?[NSString stringWithFormat:@"0%ld",seconds]:[NSString stringWithFormat:@"%ld",seconds];
NSString *minuteStr = minutes<10?[NSString stringWithFormat:@"0%ld",minutes]:[NSString stringWithFormat:@"%ld",minutes];
_timeLabel.text = [NSString stringWithFormat:@"%@:%@:%@",hourStr,minuteStr,secondStr];
}
-(BOOL)startRtmp{
[UIApplication sharedApplication].idleTimerDisabled = YES;//stop lock screen.
NSString* rtmpUrl = _currentChannel.roomURL;
if (rtmpUrl.length == 0) {
rtmpUrl = RTMP_PUBLISH_URL;
}
if (!([rtmpUrl hasPrefix:@"http:"] || [rtmpUrl hasPrefix:@"rtmp:"] )) {
[self toastTip:@"房间地址不正确!"];
return NO;
}
//是否有摄像头权限
AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (status == AVAuthorizationStatusDenied) {
[self toastTip:@"获取摄像头权限失败,请前往隐私-相机设置里面打开应用权限"];
return NO;
}
NSArray* ver = [TXRtmpApi getSDKVersion];
if ([ver count] >= 3) {
_logMsg = [NSString stringWithFormat:@"rtmp sdk version: %@.%@.%@",ver[0],ver[1],ver[2]];
[_logViewEvt setText:_logMsg];
}
if(_livePush != nil)
{
[_livePush startPush:rtmpUrl];
}
_inPushing = YES;
_currentChannel.totalTime = _totalTime;
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:_currentChannel];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:kPushging];
return YES;
}
- (void)stopRtmp {
[UIApplication sharedApplication].idleTimerDisabled = NO;
if(_livePush)
{
[_livePush stopPush];
}
}
-(void) appendLog:(NSString*) evt time:(NSDate*) date mills:(int)mil
{
NSDateFormatter* format = [[NSDateFormatter alloc] init];
format.dateFormat = @"hh:mm:ss";
NSString* time = [format stringFromDate:date];
NSString* log = [NSString stringWithFormat:@"[%@.%-3.3d] %@", time, mil, evt];
if (_logMsg == nil) {
_logMsg = @"";
}
_logMsg = [NSString stringWithFormat:@"%@\n%@", _logMsg, log];
[_logViewEvt setText:_logMsg];
}
-(void) onPushEvent:(int)EvtID WithParam:(NSDictionary*)param;
{
NSDictionary* dict = param;
dispatch_async(dispatch_get_main_queue(), ^{
if (EvtID == PUSH_ERR_NET_DISCONNECT) {
[self startRtmp];//不停的重试,只要在用户点击结束之前,都要进行重新连接操作。
// [self liveButtonPressed:_liveButton];
}
long long time = [(NSNumber*)[dict valueForKey:EVT_TIME] longLongValue];
int mil = time % 1000;
NSDate* date = [NSDate dateWithTimeIntervalSince1970:time/1000];
NSString* Msg = (NSString*)[dict valueForKey:EVT_MSG];
[self appendLog:Msg time:date mills:mil];
});
}
-(void) onNetStatus:(NSDictionary*) param
{
NSDictionary* dict = param;
dispatch_async(dispatch_get_main_queue(), ^{
int netspeed = [(NSNumber*)[dict valueForKey:NET_STATUS_NET_SPEED] intValue];
int vbitrate = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_BITRATE] intValue];
int abitrate = [(NSNumber*)[dict valueForKey:NET_STATUS_AUDIO_BITRATE] intValue];
int cachesize = [(NSNumber*)[dict valueForKey:NET_STATUS_CACHE_SIZE] intValue];
int dropsize = [(NSNumber*)[dict valueForKey:NET_STATUS_DROP_SIZE] intValue];
int jitter = [(NSNumber*)[dict valueForKey:NET_STATUS_NET_JITTER] intValue];
int fps = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_FPS] intValue];
int width = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_WIDTH] intValue];
int height = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_HEIGHT] intValue];
float cpu_usage = [(NSNumber*)[dict valueForKey:NET_STATUS_CPU_USAGE] floatValue];
NSString* log = [NSString stringWithFormat:@"CPU:%.1f%%\tRES:%d*%d\tSPD:%dkb/s\nJITT:%d\tFPS:%d\tARA:%dkb/s\nQUE:%d\tDRP:%d\tVRA:%dkb/s",
cpu_usage*100,
width,
height,
netspeed,
jitter,
fps,
abitrate,
cachesize,
dropsize,
vbitrate];
[_statusView setText:log];
});
}
#pragma mark socket delegate methods...
- (void)socketSendEndNotify {
if (_socket.isConnected) {
NSDictionary *params = @{@"cmd":@(11),
@"room":_currentChannel.room?:@"666",
@"msg":_onlineCountLabel.text,//结束时的瞬时在线人数
@"videoLen":_timeLabel.text,
@"uid":@""
};
[_socket writeDataWithParams:params tag:2];
} else {
[self connectSocket];
}
}
- (void)connectSocket {
[_socket connectToHost:_socketService.socketLiveHost onPort:_socketService.socketLivePort error:nil];
}
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
dispatch_async(dispatch_get_main_queue(), ^{
_currentRetryCount = 0;
DLog(@"socket connect success!");
NSDictionary *params = @{@"cmd":@(1),
@"uid":@"",
@"room":_currentChannel.room?:@"666",
@"name":@"",
@"avatar":@""
};
[_socket writeDataWithParams:params tag:1];
});
}
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
dispatch_async(dispatch_get_main_queue(), ^{
});
}
// 数据成功发送到服务器
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
dispatch_async(dispatch_get_main_queue(), ^{
if (tag == 1) {//登录成功了之后才继续后面的。。。。
[self socketSendEndNotify];
_socketTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(socketSendEndNotify) userInfo:nil repeats:YES];
}
});
}
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
dispatch_async(dispatch_get_main_queue(), ^{
NSError *error = nil;
NSDictionary *resDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
DLog(@"=======%@",resDic);
if (resDic && [resDic.allKeys containsObject:SOCKET_COMMAND]) {
int cmd = [[resDic objectForKey:SOCKET_COMMAND] intValue];
if (cmd == END_ACKCMD.integerValue) {
dispatch_async(dispatch_get_main_queue(), ^{
DLog(@"通知结束成功");
[self toastTip:@"通知结束成功"];
[sock disconnect];
_inPushing = NO;
[_socketTimer invalidate];
[self stopRtmp];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:kPushging];
// [self.socketService endPaly:_timeLabel.text];
_liveButton.selected = !_liveButton.selected;
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
manager.requestSerializer = [YH_HTTPRequestSerializer new];
NSLog(@"%@----%@",_currentChannel.room,_currentChannel.cid);
NSString *temp=[NSString stringWithFormat:@"%@yohocms",_currentChannel.room?:@"0"];
NSString *md5 = [self md5:temp];
NSURLSessionDataTask *task = [manager
GET:@"http://newboys.test.yoho.cn/yohoboyins/v4/qcloud/closeLive"
parameters:@{@"cid":_currentChannel.room?:@"0",@"secret":md5}
progress:NULL
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"bbbb%@",responseObject);
[self toastTip:responseObject[@"message"]];
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error:%@",error.localizedDescription);
}];
NSLog(@"%@",task.originalRequest.URL.absoluteString);
});
}
}
});
}
#pragma mark - Button actions...
- (void)hdPressed:(UIButton *)sender {
[self hideAllToolView];
_vHD.hidden = _hdButton.selected;
_hdButton.selected = !_hdButton.selected;
}
- (void)logPressed:(UIButton *)sender {
[self hideAllToolView];
_cover.hidden = _logButton.selected;
_logViewEvt.hidden = _logButton.selected;
_statusView.hidden = _logButton.selected;
_logButton.selected = !_logButton.selected;
}
- (void)accelleratePressed:(UIButton *)sender {
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
[self toastTip:@"iOS 版本低于8.0,不支持硬件加速."];
return;
}
if(_livePush != nil) {
if (_liveButton.selected) {
[self stopRtmp];
}
TXLivePushConfig * configTmp = _livePush.config;
if (configTmp.enableHWAcceleration == NO)
{
NSString* strTip = @"iOS SDK启用硬件加速.";
if (_liveButton.selected)
{
strTip = @"iOS SDK启用硬件加速,切换后会重新开始推流";
}
[self toastTip:strTip];
configTmp.enableHWAcceleration = YES;
}
else
{
NSString* strTip = @"iOS SDK停止硬件加速.";
if (_liveButton.selected)
{
strTip = @"iOS SDK停止硬件加速,切换后会重新开始推流";
}
[self toastTip:strTip];
configTmp.enableHWAcceleration = NO;
}
_livePush.config = configTmp;
if (_liveButton.selected) {
[self startRtmp];
}
}
}
- (void)beautyPressed:(UIButton *)sender {
[self hideAllToolView];
_vBeauty.hidden = sender.selected;
sender.selected = !sender.selected;
}
- (void)channelPressed:(UIButton *)sender {
if (!_channels.count) {
[self loadChannelData];
[self toastTip:@"暂无可用直播间,稍后再试!"];
return;
}
if (!_inPushing) {
[self loadChannelData];
[self toastTip:@"房间列表更新中!"];
}
[self hideAllToolView];
_channelPannel.hidden = sender.selected;
sender.selected = !sender.selected;
}
- (void)fullScreenPressed:(UIButton *)sender {
[self showFullScreen:(_fullScreenButton.selected = !_fullScreenButton.selected)];
}
- (void)showFullScreen:(BOOL)fullScreen {
_emojiPannel.hidden = fullScreen;
_barrageViewController.view.hidden = fullScreen;
}
- (void)cameraSwizzlePressed:(UIButton *)sender {
[_livePush switchCamera];
_torchButton.selected = NO;//如果后置摄像头在开了闪光灯的情况下转换为前置摄像头,闪光灯会自动关闭,此时要把闪光灯按钮的选中状态重置。
}
- (void)torchPressed:(UIButton *)sender {
if (_livePush.frontCamera) {//前置摄像头的AVcapturesession会与后置摄像头的闪光灯冲突,所以前置摄像头的情况下不允许开启闪光灯。
[self toastTip:@"前置摄像头不存在闪光灯。"];
return;
}
[_livePush toggleTorch:!sender.selected];
sender.selected = !sender.selected;
}
- (void)liveButtonPressed:(UIButton *)sender {
if (!_currentChannel) {
[self toastTip:@"请先选择房间"];
return;
}
[self hideAllToolView];
if (!_liveButton.selected) {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
manager.requestSerializer = [YH_HTTPRequestSerializer new];
NSString *temp=[NSString stringWithFormat:@"%@yohocms",_currentChannel.room?:@"0"];
NSString *md5 = [self md5:temp];
NSURLSessionDataTask *task = [manager
GET:@"http://newboys.test.yoho.cn/yohoboyins/v4/qcloud/startLive"
parameters:@{@"cid":_currentChannel.room?:@"0",@"secret":md5}
progress:NULL
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if ([responseObject[@"status"] isEqualToString:@"0"]) {
if ([self startRtmp]) {
[self toastTip:@"开始直播"];
_totalTime = 0;
_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateInfoView) userInfo:nil repeats:YES];
[_timer fire];
_liveButton.selected = !_liveButton.selected;
[self clearLog];
self.socketService.room = _currentChannel.room;
self.socketService.uid = @"9527";
self.socketService.userName = @"aaaa";
[self.socketService connect];
}else {
[self toastTip:@"直播开始失败"];
}
}else {
[self toastTip:responseObject[@"message"]];
}
NSLog(@"bbbb%@",responseObject);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"ccc");
[self toastTip:[NSString stringWithFormat:@"开始失败,原因:%@",error.localizedDescription]];
}];
NSLog(@"%@",task.originalRequest.URL.absoluteString);
} else {
if (_totalTime<122) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"直播时间小于2分钟,不可以结束直播。" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
[alert show];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定结束直播?" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
[alert show];
}
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (alertView.firstOtherButtonIndex == buttonIndex) {
[_timer invalidate];
[self socketSendEndNotify];//通知结束。
}
}
- (NSString *)md5:(NSString *)str
{
const char *cStr = [str UTF8String];
unsigned char result[16];
CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
return [NSString stringWithFormat:
@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
];
}
- (void)hideAllToolView {
_vBeauty.hidden = YES;
_vHD.hidden = YES;
_channelPannel.hidden = YES;
_beautyButton.selected = NO;
_hdButton.selected = NO;
_channelButton.selected = NO;
_cover.hidden = YES;
_logViewEvt.hidden = YES;
_statusView.hidden = YES;
_logButton.selected = NO;
}
- (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self hideAllToolView];
}
#pragma mark - UI related..
-(void) sliderValueChange:(UISlider*) obj
{
if (obj.tag == 0) { //美颜
_beauty_level = obj.value;
} else if (obj.tag == 1) { //美白
_whitening_level = obj.value;
}
[_livePush setBeautyFilterDepth:_beauty_level setWhiteningFilterDepth:_whitening_level];
}
- (void)initBeautyAndHDPannel {
CGSize size = [[UIScreen mainScreen] bounds].size;
int icon_size = size.width / 10;
_cover = [[UIView alloc]init];
_cover.frame = CGRectMake(10.0f, 55 + 2*icon_size, size.width - 20, size.height - 75 - 3 * icon_size);
_cover.backgroundColor = [UIColor whiteColor];
_cover.alpha = 0.5;
_cover.hidden = YES;
[self.view addSubview:_cover];
int logheadH = 50;
_statusView = [[UITextView alloc] initWithFrame:CGRectMake(10.0f, 55 + 2*icon_size, size.width - 20, logheadH)];
_statusView.backgroundColor = [UIColor clearColor];
_statusView.alpha = 1;
_statusView.textColor = [UIColor blackColor];
_statusView.editable = NO;
_statusView.hidden = YES;
[self.view addSubview:_statusView];
_logViewEvt = [[UITextView alloc] initWithFrame:CGRectMake(10.0f, 55 + 2*icon_size + logheadH, size.width - 20, size.height - 75 - 3 * icon_size - logheadH)];
_logViewEvt.backgroundColor = [UIColor clearColor];
_logViewEvt.alpha = 1;
_logViewEvt.textColor = [UIColor blackColor];
_logViewEvt.editable = NO;
_logViewEvt.hidden = YES;
[self.view addSubview:_logViewEvt];
//美颜拉杆浮层
_vBeauty = [[UIView alloc] init];
_vBeauty.frame = CGRectMake(0, size.height-120, size.width, 120);
[_vBeauty setBackgroundColor:[UIColor whiteColor]];
UILabel* txtBeauty = [[UILabel alloc]init];
txtBeauty.frame = CGRectMake(20, 25, 150, 150);
[txtBeauty setText:@"美颜效果"];
[txtBeauty setFont:[UIFont fontWithName:@"" size:14]];
[txtBeauty sizeToFit];
_sdBeauty = [[UISlider alloc] init];
_sdBeauty.frame = CGRectMake(txtBeauty.frame.origin.x + txtBeauty.frame.size.width + 10, 0, size.width - txtBeauty.frame.origin.x - txtBeauty.frame.size.width - 40, 60);
_sdBeauty.minimumValue = 0;
_sdBeauty.maximumValue = 9;
_sdBeauty.value = 0;
_sdBeauty.center = CGPointMake(_sdBeauty.center.x, txtBeauty.center.y);
[_sdBeauty setThumbImage:[UIImage imageNamed:@"circle"] forState:UIControlStateNormal];
[_sdBeauty setMinimumTrackTintColor:[UIColor blackColor]];
[_sdBeauty setMaximumTrackTintColor:[UIColor blackColor]];
[_sdBeauty addTarget:self action:@selector(sliderValueChange:) forControlEvents:UIControlEventValueChanged];
_sdBeauty.tag = 0;
UILabel* txtWhitening = [[UILabel alloc] init];
txtWhitening.frame = CGRectMake(20, txtBeauty.frame.origin.y + txtBeauty.frame.size.height + 25, 150, 150);
[txtWhitening setText:@"美白效果"];
[txtWhitening setFont:[UIFont fontWithName:@"" size:14]];
[txtWhitening sizeToFit];
_sdWhitening = [[UISlider alloc] init];
_sdWhitening.frame = CGRectMake(txtWhitening.frame.origin.x + txtWhitening.frame.size.width + 10, 0, size.width - txtWhitening.frame.origin.x - txtWhitening.frame.size.width - 40, 60);
_sdWhitening.minimumValue = 0;
_sdWhitening.maximumValue = 9;
_sdWhitening.center = CGPointMake(_sdWhitening.center.x, txtWhitening.center.y);
[_sdWhitening setThumbImage:[UIImage imageNamed:@"circle"] forState:UIControlStateNormal];
[_sdWhitening setMinimumTrackTintColor:[UIColor blackColor]];
[_sdWhitening setMaximumTrackTintColor:[UIColor blackColor]];
[_sdWhitening addTarget:self action:@selector(sliderValueChange:) forControlEvents:UIControlEventValueChanged];
_sdWhitening.tag = 1;
[_vBeauty addSubview:txtBeauty];
[_vBeauty addSubview:_sdBeauty];
[_vBeauty addSubview:txtWhitening];
[_vBeauty addSubview:_sdWhitening];
_vBeauty.hidden = YES;
[self.view addSubview: _vBeauty];
// 清晰度选项: 720p - 640 - 640+ (此处使用了三个普通按钮来模拟单选框, 目的是跟android demo 保持界面风格一致)
_vHD = [[UIView alloc]init];
_vHD.frame = CGRectMake(0, size.height-120, size.width, 120);
[_vHD setBackgroundColor:[UIColor whiteColor]];
UILabel* txtHD= [[UILabel alloc]init];
txtHD.frame = CGRectMake(0, 0, size.width, 50);
[txtHD setText:@"清晰度"];
[txtHD setFont:[UIFont fontWithName:@"" size:14]];
txtHD.textAlignment = NSTextAlignmentCenter;
[_vHD addSubview:txtHD];
int gap = 30;
int width = (size.width - gap*3 - 20) / 4;
_radioBtnHD = [UIButton buttonWithType:UIButtonTypeCustom];
_radioBtnHD.frame = CGRectMake(10, 60, width, 40);
[_radioBtnHD setTitle:@"720p" forState:UIControlStateNormal];
[_radioBtnHD addTarget:self action:@selector(changeHD:) forControlEvents:UIControlEventTouchUpInside];
_radioBtnHD2 = [UIButton buttonWithType:UIButtonTypeCustom];
_radioBtnHD2.frame = CGRectMake(10 + gap + width, 60, width, 40);
[_radioBtnHD2 setTitle:@"540p" forState:UIControlStateNormal];
[_radioBtnHD2 addTarget:self action:@selector(changeHD:) forControlEvents:UIControlEventTouchUpInside];
_radioBtnSD = [UIButton buttonWithType:UIButtonTypeCustom];
_radioBtnSD.frame = CGRectMake(10 + (gap + width)*2, 60, width, 40);
[_radioBtnSD setTitle:@"360p" forState:UIControlStateNormal];
[_radioBtnSD addTarget:self action:@selector(changeHD:) forControlEvents:UIControlEventTouchUpInside];
_radioBtnAUTO = [UIButton buttonWithType:UIButtonTypeCustom];
_radioBtnAUTO.frame = CGRectMake(size.width - 10 - width, 60, width, 40);
[_radioBtnAUTO setTitle:@"360+" forState:UIControlStateNormal];
[_radioBtnAUTO addTarget:self action:@selector(changeHD:) forControlEvents:UIControlEventTouchUpInside];
[_vHD addSubview:_radioBtnHD];
[_vHD addSubview:_radioBtnHD2];
[_vHD addSubview:_radioBtnSD];
[_vHD addSubview:_radioBtnAUTO];
_vHD.hidden = YES;
[self.view addSubview: _vHD];
// DEMO 默认采用 640 * 360 分辨率, 避免在4S等机型上出现编码不足
int _hd_level = [self isSuitableMachine] ? HD_LEVEL_720P : HD_LEVEL_360_PLUS;
[self setHDUI:_hd_level];
}
-(void) setHDUI:(int) level
{
switch (level) {
case HD_LEVEL_720P:
[_radioBtnHD setBackgroundImage:[UIImage imageNamed:@"black"] forState:UIControlStateNormal];
[_radioBtnHD2 setBackgroundImage:[UIImage imageNamed:@"white"] forState:UIControlStateNormal];
[_radioBtnSD setBackgroundImage:[UIImage imageNamed:@"white"] forState:UIControlStateNormal];
[_radioBtnAUTO setBackgroundImage:[UIImage imageNamed:@"white"] forState:UIControlStateNormal];
[_radioBtnHD setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[_radioBtnHD2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_radioBtnSD setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_radioBtnAUTO setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_hdButton setTitle:@"高清" forState:UIControlStateNormal];
break;
case HD_LEVEL_540P:
[_radioBtnHD setBackgroundImage:[UIImage imageNamed:@"white"] forState:UIControlStateNormal];
[_radioBtnHD2 setBackgroundImage:[UIImage imageNamed:@"black"] forState:UIControlStateNormal];
[_radioBtnSD setBackgroundImage:[UIImage imageNamed:@"white"] forState:UIControlStateNormal];
[_radioBtnAUTO setBackgroundImage:[UIImage imageNamed:@"white"] forState:UIControlStateNormal];
[_radioBtnHD setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_radioBtnHD2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[_radioBtnSD setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_radioBtnAUTO setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_hdButton setTitle:@"高清" forState:UIControlStateNormal];
break;
case HD_LEVEL_360P:
[_radioBtnHD setBackgroundImage:[UIImage imageNamed:@"white"] forState:UIControlStateNormal];
[_radioBtnHD2 setBackgroundImage:[UIImage imageNamed:@"white"] forState:UIControlStateNormal];
[_radioBtnSD setBackgroundImage:[UIImage imageNamed:@"black"] forState:UIControlStateNormal];
[_radioBtnAUTO setBackgroundImage:[UIImage imageNamed:@"white"] forState:UIControlStateNormal];
[_radioBtnHD setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_radioBtnHD2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_radioBtnSD setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[_radioBtnAUTO setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_hdButton setTitle:@"标清" forState:UIControlStateNormal];
break;
case HD_LEVEL_360_PLUS:
[_radioBtnHD setBackgroundImage:[UIImage imageNamed:@"white"] forState:UIControlStateNormal];
[_radioBtnHD2 setBackgroundImage:[UIImage imageNamed:@"white"] forState:UIControlStateNormal];
[_radioBtnSD setBackgroundImage:[UIImage imageNamed:@"white"] forState:UIControlStateNormal];
[_radioBtnAUTO setBackgroundImage:[UIImage imageNamed:@"black"] forState:UIControlStateNormal];
[_radioBtnHD setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_radioBtnHD2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_radioBtnSD setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_radioBtnAUTO setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[_hdButton setTitle:@"普清" forState:UIControlStateNormal];
default:
break;
}
}
// iphone 6 及以上机型适合开启720p, 否则20帧的帧率可能无法达到, 这种"流畅不足,清晰有余"的效果并不好
-(BOOL) isSuitableMachine
{
int mib[2] = {CTL_HW, HW_MACHINE};
size_t len = 0;
char* machine;
sysctl(mib, 2, NULL, &len, NULL, 0);
machine = (char*)malloc(len);
sysctl(mib, 2, machine, &len, NULL, 0);
NSString* platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
free(machine);
if ([platform length] > 6) {
NSString * platNum = [NSString stringWithFormat:@"%C", [platform characterAtIndex: 6 ]];
return ([platNum intValue] >= 7);
} else {
return NO;
}
}
-(void) changeHD:(UIButton*) btn
{
if ([btn.titleLabel.text isEqualToString:@"720p"] && NO == [self isSuitableMachine]) {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @"硬件加速"
message: @"iphone 6 及以上机型适合开启720p!"
delegate: nil
cancelButtonTitle: @"确认"
otherButtonTitles: nil];
[alert show];
return;
}
if (_liveButton.selected) {
[self stopRtmp];
}
int _hd_level;
if ([btn.titleLabel.text isEqualToString:@"720p"]) {
_hd_level = HD_LEVEL_720P;
TXLivePushConfig* _config = _livePush.config;
_config.videoBitratePIN = 1500;
_config.videoResolution = [self isSuitableMachine ] ? VIDEO_RESOLUTION_1280_720 : VIDEO_RESOLUTION_960_540;
_config.enableAutoBitrate = NO;
[_livePush setConfig:_config];
}else if ([btn.titleLabel.text isEqualToString:@"540p"]) {
_hd_level = HD_LEVEL_540P;
TXLivePushConfig* _config = _livePush.config;
_config.videoBitratePIN = 800;
_config.videoResolution = VIDEO_RESOLUTION_960_540;
_config.enableAutoBitrate = NO;
[_livePush setConfig:_config];
}else if ([btn.titleLabel.text isEqualToString:@"360p"]) {
_hd_level = HD_LEVEL_360P;
TXLivePushConfig* _config = _livePush.config;
_config.videoBitratePIN = 600;
_config.videoResolution = VIDEO_RESOLUTION_640_360;
_config.enableAutoBitrate = NO;
[_livePush setConfig:_config];
} else if ([btn.titleLabel.text isEqualToString:@"360+"]) {
_hd_level = HD_LEVEL_360_PLUS;
TXLivePushConfig* _config = _livePush.config;
_config.videoBitrateMin = 100;
_config.videoBitrateMax = 1200;
_config.enableAutoBitrate = YES;
_config.videoResolution = VIDEO_RESOLUTION_640_360;
[_livePush setConfig:_config]; // 此模式下设置bitrate无效
}
[self setHDUI:_hd_level];
_vHD.hidden = YES;
if (_liveButton.selected) {
[self startRtmp];
}
}
- (void)initChannelPannel {
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:kPushging];
if (data.length) {
_currentChannel = [NSKeyedUnarchiver unarchiveObjectWithData:data];
}
_channelPannel = [UIView new];
_channelPannel.backgroundColor = [UIColor clearColor];
[self.view addSubview:_channelPannel];
UILabel *titleLabel = [UILabel new];
titleLabel.backgroundColor = [UIColor whiteColor];
titleLabel.font = [UIFont boldSystemFontOfSize:16];
titleLabel.textAlignment = NSTextAlignmentCenter;
titleLabel.text = @"直播间";
titleLabel.layer.borderColor = [UIColor lightGrayColor].CGColor;
titleLabel.layer.borderWidth = 0.5;
[_channelPannel addSubview:titleLabel];
_liveButton = [UIButton buttonWithType:UIButtonTypeCustom];
_liveButton.backgroundColor = [UIColor whiteColor];
[_liveButton addTarget:self action:@selector(liveButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[_liveButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_liveButton setTitle:@"开始直播" forState:UIControlStateNormal];
[_liveButton setTitle:@"结束直播" forState:UIControlStateSelected];
_liveButton.titleLabel.font = [UIFont systemFontOfSize:16];
[_liveButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
[_channelPannel addSubview:_liveButton];
if (_currentChannel) {
_inPushing = YES;
_liveButton.selected = YES;
[_liveButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
}
_channelTable = [UITableView new];
_channelTable.tableFooterView = [UIView new];
_channelTable.backgroundColor = [UIColor whiteColor];
_channelTable.delegate = self;
_channelTable.dataSource = self;
[_channelPannel addSubview:_channelTable];
[_channelPannel autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:10];
[_channelPannel autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:10];
[_channelPannel autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:60];
[_channelPannel autoSetDimension:ALDimensionHeight toSize:250];
[titleLabel autoPinEdgeToSuperviewEdge:ALEdgeTop];
[titleLabel autoPinEdgeToSuperviewEdge:ALEdgeLeft];
[titleLabel autoPinEdgeToSuperviewEdge:ALEdgeRight];
[titleLabel autoSetDimension:ALDimensionHeight toSize:40];
[_liveButton autoPinEdgeToSuperviewEdge:ALEdgeBottom];
[_liveButton autoPinEdgeToSuperviewEdge:ALEdgeLeft];
[_liveButton autoPinEdgeToSuperviewEdge:ALEdgeRight];
[_liveButton autoSetDimension:ALDimensionHeight toSize:40];
[_channelTable autoPinEdgeToSuperviewEdge:ALEdgeLeft];
[_channelTable autoPinEdgeToSuperviewEdge:ALEdgeRight];
[_channelTable autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:titleLabel];
[_channelTable autoPinEdge:ALEdgeBottom toEdge:ALEdgeTop ofView:_liveButton withOffset:-10];
_channelPannel.hidden = YES;
}
/**
* @author Kennaki Kai, 16-06-12 10:06:20
*
* @brief Smile faces...
*
* @since 1.0
*/
- (void)initEmojiPannel {
_emojiPannel = [UIView new];
[self.view addSubview:_emojiPannel];
_emojiImage = [UIImageView new];
_emojiImage.image = [UIImage imageNamed:@"emoji_smile"];
[_emojiPannel addSubview:_emojiImage];
_emojiCountLabel = [UILabel new];
_emojiCountLabel.font = [UIFont systemFontOfSize:10];
_emojiCountLabel.textColor =[UIColor whiteColor];
_emojiCountLabel.textAlignment = NSTextAlignmentCenter;
_emojiCountLabel.shadowColor = [UIColor blackColor];
_emojiCountLabel.shadowOffset = CGSizeMake(1, 1);
[_emojiPannel addSubview:_emojiCountLabel];
_emojiCountLabel.text = @"0";
[_emojiPannel autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:15];
[_emojiPannel autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:75];
[_emojiPannel autoSetDimensionsToSize:CGSizeMake(55, 80)];
[_emojiImage autoPinEdgeToSuperviewEdge:ALEdgeTop];
[_emojiImage autoPinEdgeToSuperviewEdge:ALEdgeRight];
[_emojiImage autoPinEdgeToSuperviewEdge:ALEdgeLeft];
[_emojiImage autoSetDimension:ALDimensionHeight toSize:55];
[_emojiCountLabel autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:_emojiImage];
[_emojiCountLabel autoPinEdgeToSuperviewEdge:ALEdgeRight];
[_emojiCountLabel autoPinEdgeToSuperviewEdge:ALEdgeLeft];
[_emojiCountLabel autoSetDimension:ALDimensionHeight toSize:25];
}
- (void)initInfoPannel {
_infoPannel = [UIView new];
[self.view addSubview:_infoPannel];
_onlineCountLabel = [UILabel new];
_onlineCountLabel.shadowOffset = CGSizeMake(1, 1);
_onlineCountLabel.textColor = [UIColor whiteColor];
_onlineCountLabel.shadowColor = [UIColor blackColor];
_onlineCountLabel.font = [UIFont systemFontOfSize:14];
[_infoPannel addSubview:_onlineCountLabel];
_onlineCountLabel.text = @"0人在线";
_timeLabel = [UILabel new];
_timeLabel.shadowColor = [UIColor blackColor];
_timeLabel.shadowOffset = CGSizeMake(1, 1);
_timeLabel.font = [UIFont systemFontOfSize:10];
_timeLabel.textColor = [UIColor whiteColor];
[_infoPannel addSubview:_timeLabel];
_timeLabel.text = @"00:00:00";
[_infoPannel autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:15];
[_infoPannel autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:15];
[_infoPannel autoSetDimensionsToSize:CGSizeMake(300, 34)];
[_onlineCountLabel autoPinEdgeToSuperviewEdge:ALEdgeLeft];
[_onlineCountLabel autoPinEdgeToSuperviewEdge:ALEdgeTop];
[_timeLabel autoPinEdgeToSuperviewEdge:ALEdgeLeft];
[_timeLabel autoPinEdgeToSuperviewEdge:ALEdgeBottom];
}
/**
* @author Kennaki Kai, 16-06-21 16:06:14
*
* @brief 初始化弹幕视图
*
* @since 1.0
*/
- (void)initBarrageView {
[self addChildViewController:self.barrageViewController];
[self.view addSubview:self.barrageViewController.view];
// self.barrageViewController.view.left = SCREEN_WIDTH;
// self.barrageViewController.view.backgroundColor = [UIColor redColor];
self.socketService.barrageViewController = self.barrageViewController;
}
/**
* @author Kennaki, 16-06-07 13:06:45
*
* @brief Init user interface.
*
* @since 1.0
*/
- (void)initUI {
[self initEmojiPannel];
[self initBarrageView];
[self initInfoPannel];
_fullScreenButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_fullScreenButton addTarget:self action:@selector(fullScreenPressed:) forControlEvents:UIControlEventTouchUpInside];
[_fullScreenButton setImage:[UIImage imageNamed:@"icon_Full-Screen"] forState:UIControlStateNormal];
[_fullScreenButton setImage:[UIImage imageNamed:@"icon_Exit-Full-Screen"] forState:UIControlStateSelected];
[self.view addSubview:_fullScreenButton];
_cameraSwitchButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_cameraSwitchButton addTarget:self action:@selector(cameraSwizzlePressed:) forControlEvents:UIControlEventTouchUpInside];
[_cameraSwitchButton setImage:[UIImage imageNamed:@"icon_Switching"] forState:UIControlStateNormal];
[self.view addSubview:_cameraSwitchButton];
_torchButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_torchButton addTarget:self action:@selector(torchPressed:) forControlEvents:UIControlEventTouchUpInside];
[_torchButton setImage:[UIImage imageNamed:@"icon_photoflash"] forState:UIControlStateNormal];
[_torchButton setImage:[UIImage imageNamed:@"icon_no-flash"] forState:UIControlStateSelected];
[self.view addSubview:_torchButton];
UIView *bottomToolView = [UIView new];
bottomToolView.backgroundColor = [UIColor clearColor];
[self.view addSubview:bottomToolView];
[bottomToolView autoPinEdgeToSuperviewEdge:ALEdgeRight];
[bottomToolView autoPinEdgeToSuperviewEdge:ALEdgeLeft];
[bottomToolView autoPinEdgeToSuperviewEdge:ALEdgeBottom];
[bottomToolView autoSetDimension:ALDimensionHeight toSize:50];
UIView *line = [UIView new];
line.backgroundColor = [UIColor whiteColor];
[bottomToolView addSubview:line];
[line autoPinEdgeToSuperviewEdge:ALEdgeTop];
[line autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:10];
[line autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:10];
[line autoSetDimension:ALDimensionHeight toSize:0.5];
_channelButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_channelButton addTarget:self action:@selector(channelPressed:) forControlEvents:UIControlEventTouchUpInside];
[_channelButton setTitle:@"频道" forState:UIControlStateNormal];
[bottomToolView addSubview:_channelButton];
_beautyButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_beautyButton addTarget:self action:@selector(beautyPressed:) forControlEvents:UIControlEventTouchUpInside];
[_beautyButton setTitle:@"美颜" forState:UIControlStateNormal];
[bottomToolView addSubview:_beautyButton];
_accellerateButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_accellerateButton addTarget:self action:@selector(accelleratePressed:) forControlEvents:UIControlEventTouchUpInside];
[_accellerateButton setTitle:@"加速" forState:UIControlStateNormal];
[bottomToolView addSubview:_accellerateButton];
_logButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_logButton addTarget:self action:@selector(logPressed:) forControlEvents:UIControlEventTouchUpInside];
[_logButton setTitle:@"Log" forState:UIControlStateNormal];
[bottomToolView addSubview:_logButton];
_hdButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_hdButton addTarget:self action:@selector(hdPressed:) forControlEvents:UIControlEventTouchUpInside];
[_hdButton setTitle:@"高清" forState:UIControlStateNormal];
[bottomToolView addSubview:_hdButton];
NSArray *toolButtons = @[_fullScreenButton,_cameraSwitchButton,_torchButton,_channelButton,_beautyButton,_accellerateButton,_logButton,_hdButton];
[toolButtons autoSetViewsDimensionsToSize:CGSizeMake(30, 30)];
for (UIButton *btn in toolButtons) {
btn.backgroundColor = [UIColor colorWithWhite:1 alpha:0.7];
btn.titleLabel.font = [UIFont systemFontOfSize:12];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
btn.layer.cornerRadius = 15;
btn.clipsToBounds = YES;
}
[_fullScreenButton autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:15];
[_fullScreenButton autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:15];
[_cameraSwitchButton autoPinEdge:ALEdgeRight toEdge:ALEdgeLeft ofView:_fullScreenButton withOffset:-15];
[_cameraSwitchButton autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:15];
[_torchButton autoPinEdge:ALEdgeRight toEdge:ALEdgeLeft ofView:_cameraSwitchButton withOffset:-15];
[_torchButton autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:15];
NSArray *bottomAry = @[_channelButton,_beautyButton,_accellerateButton,_logButton,_hdButton];
[bottomAry autoDistributeViewsAlongAxis:ALAxisHorizontal alignedTo:ALAttributeHorizontal withFixedSize:30];
for (UIButton *btn in bottomAry) {
[btn autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:10];
}
[self initBeautyAndHDPannel];
[self initChannelPannel];
}
#pragma mark - table view protocols...
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _channels.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
YH_ChannelCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YH_ChannelCell"];
if (!cell) {
cell = [[YH_ChannelCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"YH_ChannelCell"];
}
[cell bindChannelTitle:_channels[indexPath.row].roomTitle selected:(indexPath.row==_currentChannelIndex)];
return cell;
return [UITableViewCell new];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 40;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (_inPushing) {
return;//正在直播的情况下不得选择另外的房间,否则在通知结束的时候无法保证参数正确。。。
}
_currentChannelIndex = indexPath.row;
_currentChannel = _channels[_currentChannelIndex];
[_liveButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_channelTable reloadData];
}
- (void) toastTip:(NSString*)toastInfo
{
CGRect frameRC = [[UIScreen mainScreen] bounds];
frameRC.origin.y = frameRC.size.height - 110;
frameRC.size.height -= 110;
__block UITextView * toastView = [[UITextView alloc] init];
toastView.editable = NO;
toastView.selectable = NO;
frameRC.size.height = [self heightForString:toastView andWidth:frameRC.size.width];
toastView.frame = frameRC;
toastView.text = toastInfo;
toastView.backgroundColor = [UIColor whiteColor];
toastView.alpha = 0.5;
[self.view addSubview:toastView];
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(){
[toastView removeFromSuperview];
toastView = nil;
});
}
- (float) heightForString:(UITextView *)textView andWidth:(float)width{
CGSize sizeToFit = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
return sizeToFit.height;
}
@end