forked from CommercialTribe/react-native-opentok
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RCTOpenTokPublisherView.m
284 lines (234 loc) · 7.86 KB
/
RCTOpenTokPublisherView.m
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
/**
* Copyright (c) 2015-present, Callstack Sp z o.o.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
@import UIKit;
#import "RCTOpenTokPublisherView.h"
#import "OTKBasicVideoCapturer.h"
#import "RCTEventDispatcher.h"
#import "RCTUtils.h"
#import <OpenTok/OpenTok.h>
@interface RCTOpenTokPublisherView () <OTSessionDelegate, OTPublisherDelegate>
@end
@implementation RCTOpenTokPublisherView {
OTSession *_session;
OTPublisher *_publisher;
BOOL _isSessionCreated;
BOOL _isPaused;
BOOL _isPublished;
}
/**
* Create session after all props were passed
*/
- (void)didMoveToWindow {
[super didMoveToSuperview];
if (!_isSessionCreated) {
[self createSession];
}
}
/**
* Creates a new session with a given apiKey, sessionID and token
*
* Calls `onStartFailure` in case an error happens during initial creation.
*
* Otherwise, `onSessionCreated` callback is called asynchronously
*/
- (void) createSession {
_isPaused = NO;
_session = [[OTSession alloc] initWithApiKey:_apiKey sessionId:_sessionId delegate:self];
OTError *error = nil;
[_session connectWithToken:_token error:&error];
if (error) {
_onPublishError(RCTJSErrorFromNSError(error));
} else {
_isSessionCreated = YES;
}
}
/**
* Creates an instance of `OTPublisher` and publishes stream to the current
* session
*
* Calls `onPublishError` in case of an error, otherwise, a camera preview is inserted
* inside the mounted view
*/
- (void)startPublishing {
_publisher = [[OTPublisher alloc] initWithDelegate:self
name: @"My Video"
cameraResolution: _cameraResolution
cameraFrameRate: _cameraFrameRate];
_publisher.publishAudio = YES;
_publisher.publishVideo = _videoEnabled;
_publisher.audioFallbackEnabled = YES;
OTError *error = nil;
[_session publish:_publisher error:&error];
if (error) {
_onPublishError(RCTJSErrorFromNSError(error));
return;
}
[self attachPublisherView];
_publisher.videoCapture = [[OTKBasicVideoCapturer alloc]
initWithPreset: [self getCapturePreset:_cameraResolution]
andDesiredFrameRate:_cameraFrameRate];
}
- (NSString *) getCapturePreset:(NSInteger) resolution
{
if (resolution == OTCameraCaptureResolutionLow) {
return AVCaptureSessionPreset352x288;
} else if (resolution == OTCameraCaptureResolutionMedium) {
return AVCaptureSessionPreset640x480;
} else if (resolution == OTCameraCaptureResolutionHigh) {
return AVCaptureSessionPreset1280x720;
}
[NSException raise:@"Invalid camera resolution value" format:@" %ld is invalid", (long)resolution];
return @"";
}
- (void)pausePublish{
_isPaused = YES;
OTError* error = nil;
[_session unpublish:_publisher error:&error];
if (error) {
NSLog(@"pausePublish with error: (%@)", error);
}
}
- (void)resumePublish{
_isPaused = NO;
// for web we could preserve the publisher, but it doesnt seem to work here.
// So we need to recreate the publisher
dispatch_async(dispatch_get_main_queue(), ^{
[self startPublishing];
});
}
- (void)stopPublish{
_isPaused = NO;
if (_isPublished) {
OTError* error = nil;
[_session unpublish:_publisher error:&error];
if (error) {
NSLog(@"stopPublish failed with error: (%@)", error);
}
}
}
/**
* Attaches publisher preview
*/
- (void)attachPublisherView {
[_publisher.view setFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
_publisher.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self addSubview:_publisher.view];
}
/**
* Cleans up publisher
*/
- (void)cleanupPublisher {
if (! _isPaused) {
[_publisher.view removeFromSuperview];
_publisher = nil;
}
}
- (void) saveThumbnail {
[self screenShotImageWithView:_publisher.view];
}
- (UIView *) screenShotViewWithView:(UIView *)view
{
return [view snapshotViewAfterScreenUpdates:YES];
}
- (void) screenShotImageWithView :(UIView *) view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [UIScreen mainScreen].scale);
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
UIImage *originalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImage *image = [[UIImage alloc] initWithCGImage: originalImage.CGImage
scale: originalImage.scale
orientation: UIImageOrientationUpMirrored];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"OpentokLastThumbnail.png"];
[UIImageJPEGRepresentation(image, 1.0) writeToFile:filePath atomically:YES];
_onThumbnailReady(@{
@"filePath": filePath,
});
}
#pragma mark - OTSession delegate callbacks
/**
* When session is created, we start publishing straight away
*/
- (void)sessionDidConnect:(OTSession*)session {
_onSessionDidConnect(@{
@"sessionId": session.sessionId,
});
[self startPublishing];
}
- (void)sessionDidDisconnect:(OTSession*)session {
_onSessionDidDisconnect(@{
@"sessionId": session.sessionId,
});
}
/**
* @todo multiple streams in a session are out of scope
* for our use-cases. To be implemented later.
*/
- (void)session:(OTSession*)session streamCreated:(OTStream *)stream {}
- (void)session:(OTSession*)session streamDestroyed:(OTStream *)stream {}
/**
* Called when another client connects to the session
*/
- (void)session:(OTSession *)session connectionCreated:(OTConnection *)connection {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss ZZZ yyyy"];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *creationTimeString = [dateFormatter stringFromDate:connection.creationTime];
_onClientConnected(@{
@"connectionId": connection.connectionId,
@"creationTime": creationTimeString,
@"data": connection.data,
});
}
/**
* Called when client disconnects from the session
*/
- (void)session:(OTSession *)session connectionDestroyed:(OTConnection *)connection {
_onClientDisconnected(@{
@"connectionId": connection.connectionId,
});
}
- (void)session:(OTSession*)session didFailWithError:(OTError*)error {
_onPublishError(RCTJSErrorFromNSError(error));
}
#pragma mark - OTSession delegate - archive callbacks
- (void)session:(OTSession *)session archiveStartedWithId:(NSString *)archiveId name:(NSString *)name {
[self saveThumbnail];
_onArchiveStarted(@{
@"archiveId": archiveId,
@"name": name,
});
}
- (void)session:(OTSession *)session archiveStoppedWithId:(NSString *)archiveId {
_onArchiveStopped(@{
@"archiveId": archiveId,
});
}
#pragma mark - OTPublisher delegate callbacks
- (void)publisher:(OTPublisherKit*)publisher streamCreated:(OTStream *)stream {
_isPublished = YES;
_onPublishStart(@{});
}
- (void)publisher:(OTPublisherKit*)publisher streamDestroyed:(OTStream *)stream {
_isPublished = NO;
_onPublishStop(@{});
[self cleanupPublisher];
}
- (void)publisher:(OTPublisherKit*)publisher didFailWithError:(OTError*)error {
_isPublished = NO;
_onPublishError(RCTJSErrorFromNSError(error));
[self cleanupPublisher];
}
- (void)removeFromSuperview {
_isSessionCreated = NO;
[self cleanupPublisher];
[_session disconnect:nil];
[super removeFromSuperview];
}
@end