-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSyphonClientConnectionManager.m
More file actions
433 lines (392 loc) · 12.7 KB
/
SyphonClientConnectionManager.m
File metadata and controls
433 lines (392 loc) · 12.7 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
/*
SyphonClientConnectionManager.m
Syphon
Copyright 2010-2011 bangnoise (Tom Butterworth) & vade (Anton Marini).
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "SyphonClientConnectionManager.h"
#import "SyphonPrivate.h"
#import <OpenGL/gl.h>
#pragma mark Shared Instances
static OSSpinLock _lookupTableLock = OS_SPINLOCK_INIT;
static NSMapTable *_lookupTable;
static id SyphonClientPrivateCopyInstance(NSString *uuid)
{
id result = nil;
OSSpinLockLock(&_lookupTableLock);
if (uuid) result = [_lookupTable objectForKey:uuid];
[result retain];
OSSpinLockUnlock(&_lookupTableLock);
return result;
}
static void SyphonClientPrivateInsertInstance(id instance, NSString *uuid)
{
OSSpinLockLock(&_lookupTableLock);
if (uuid)
{
if (!_lookupTable) _lookupTable = [[NSMapTable alloc] initWithKeyOptions:NSMapTableStrongMemory valueOptions:NSMapTableZeroingWeakMemory capacity:1];
[_lookupTable setObject:instance forKey:uuid];
}
OSSpinLockUnlock(&_lookupTableLock);
}
static void SyphonClientPrivateRemoveInstance(id instance, NSString *uuid)
{
OSSpinLockLock(&_lookupTableLock);
if (uuid) [_lookupTable removeObjectForKey:uuid];
if ([_lookupTable count] == 0)
{
[_lookupTable release];
_lookupTable = nil;
}
OSSpinLockUnlock(&_lookupTableLock);
}
@interface SyphonClientConnectionManager (Private)
- (void)setServerName:(NSString *)name;
- (void)publishNewFrame;
- (void)setSurfaceID:(IOSurfaceID)surfaceID;
- (void)updateSurface:(NSDictionary *)description;
- (IOSurfaceRef)surfaceHavingLock;
- (void)endConnectionHavingLock:(BOOL)hasLock;
@end
@implementation SyphonClientConnectionManager
- (id)initWithServerDescription:(NSDictionary *)description
{
self = [super init];
if (self)
{
NSString *serverUUID = [description objectForKey:SyphonServerDescriptionUUIDKey];
// for newFrame Handler, default values for now.
_internalFormat = GL_RGBA8;
_format = GL_BGRA;
_type = GL_UNSIGNED_INT_8_8_8_8_REV;
// Return an existing instance for this server if we have one
id existing = SyphonClientPrivateCopyInstance(serverUUID);
if (existing)
{
[self release];
return existing;
}
NSArray *surfaces = [description objectForKey:SyphonServerDescriptionSurfacesKey];
BOOL hasIOSurface = NO;
for (NSDictionary *surface in surfaces)
{
if ([[surface objectForKey:SyphonSurfaceType] isEqualToString:SyphonSurfaceTypeIOSurface]) hasIOSurface = YES;
}
if (!hasIOSurface)
{
[self release];
return nil;
}
_lock = OS_SPINLOCK_INIT;
_serverDescription = [[NSMutableDictionary alloc] initWithDictionary:description];
_myUUID = SyphonCreateUUIDString();
SyphonClientPrivateInsertInstance(self, serverUUID);
_frames = [[NSMapTable mapTableWithKeyOptions:(NSPointerFunctionsOpaquePersonality | NSPointerFunctionsOpaqueMemory)
valueOptions:(NSPointerFunctionsObjectPersonality | NSPointerFunctionsStrongMemory)] retain];
}
return self;
}
- (void)finalize
{
if (_frameQueue) dispatch_release(_frameQueue);
[super finalize];
}
- (void) dealloc
{
SyphonClientPrivateRemoveInstance(self, [_serverDescription objectForKey:SyphonServerDescriptionUUIDKey]);
[_frames release];
if (_frameQueue) dispatch_release(_frameQueue);
[_frameClients release];
[_serverDescription release];
[_myUUID release];
[super dealloc];
}
- (void)endConnectionHavingLock:(BOOL)hasLock
{
SYPHONLOG(@"Ending connection");
SyphonMessageReceiver *connection;
IOSurfaceRef surface;
// we copy and clear ivars inside the lock, release them outside it
if (!hasLock) OSSpinLockLock(&_lock);
connection = _connection;
_connection = nil;
_active = NO;
surface = _surface;
_surface = NULL;
[_frames removeAllObjects];
if (!hasLock) OSSpinLockUnlock(&_lock);
[connection invalidate];
[connection release];
if (surface) CFRelease(surface);
}
- (BOOL)isValid
{
BOOL result;
OSSpinLockLock(&_lock);
result = _active;
OSSpinLockUnlock(&_lock);
return result;
}
- (void)addInfoClient:(id)client
{
OSSpinLockLock(&_lock);
_infoClientCount++;
BOOL shouldSendAdd = NO;
NSString *serverUUID = nil;
if (_infoClientCount == 1)
{
// set up a connection to receive and deal with messages from the server
_connection = [[SyphonMessageReceiver alloc] initForName:_myUUID protocol:SyphonMessagingProtocolCFMessage handler:^(id data, uint32_t type) {
switch (type) {
case SyphonMessageTypeNewFrame:
[self publishNewFrame];
break;
case SyphonMessageTypeUpdateServerName:
[self setServerName:(NSString *)data];
break;
case SyphonMessageTypeUpdateSurfaceID:
[self setSurfaceID:[(NSNumber *)data unsignedIntValue]];
break;
case SyphonMessageTypeRetireServer:
[self endConnectionHavingLock:NO];
break;
case SyphonMessageTypeUpdateSurfaceDescription:
[self updateSurface:(NSDictionary *)data];
break;
default:
SYPHONLOG(@"Unknown message type #%u received", type);
break;
}
}];
if (_connection != nil)
{
serverUUID = [_serverDescription objectForKey:SyphonServerDescriptionUUIDKey];
_active = shouldSendAdd = YES;
}
}
OSSpinLockUnlock(&_lock);
// We can do this outside the lock because we're not using any protected resources
if (shouldSendAdd)
{
SYPHONLOG(@"Registering for info updates");
SyphonMessageSender *sender = [[SyphonMessageSender alloc] initForName:serverUUID
protocol:SyphonMessagingProtocolCFMessage
invalidationHandler:nil];
if (sender == nil)
{
SYPHONLOG(@"Failed to create connection to server with uuid:%@", serverUUID);
[self endConnectionHavingLock:NO];
}
[sender send:_myUUID ofType:SyphonMessageTypeAddClientForInfo];
[sender release];
}
}
- (void)removeInfoClient:(id)client
{
OSSpinLockLock(&_lock);
_infoClientCount--;
if (_infoClientCount == 0)
{
// Remove ourself from the server
NSString *serverUUID = [_serverDescription objectForKey:SyphonServerDescriptionUUIDKey];
if (_active)
{
SYPHONLOG(@"De-registering for info updates");
SyphonMessageSender *sender = [[SyphonMessageSender alloc] initForName:serverUUID
protocol:SyphonMessagingProtocolCFMessage
invalidationHandler:nil];
[sender send:_myUUID ofType:SyphonMessageTypeRemoveClientForInfo];
[sender release];
[self endConnectionHavingLock:YES];
}
}
OSSpinLockUnlock(&_lock);
}
- (void)addFrameClient:(id)client
{
OSSpinLockLock(&_lock);
if (_frameQueue == nil)
{
_frameQueue = dispatch_queue_create([_myUUID cStringUsingEncoding:NSUTF8StringEncoding], 0);
_frameClients = [[NSHashTable hashTableWithWeakObjects] retain];
}
OSSpinLockUnlock(&_lock);
// only access _frameClients within the queue
dispatch_sync(_frameQueue, ^{
[_frameClients addObject:client];
});
if (OSAtomicIncrement32(&_handlerCount) == 1)
{
SYPHONLOG(@"Registering for frame updates");
SyphonMessageSender *sender = [[SyphonMessageSender alloc] initForName:[self.serverDescription objectForKey:SyphonServerDescriptionUUIDKey]
protocol:SyphonMessagingProtocolCFMessage
invalidationHandler:nil];
if (sender == nil)
{
SYPHONLOG(@"Failed to create connection to server with uuid:%@", [self.serverDescription objectForKey:SyphonServerDescriptionUUIDKey]);
[self endConnectionHavingLock:NO];
}
[sender send:_myUUID ofType:SyphonMessageTypeAddClientForFrames];
[sender release];
}
}
- (void)removeFrameClient:(id)client
{
dispatch_sync(_frameQueue, ^{
[_frameClients removeObject:client];
});
if (OSAtomicDecrement32(&_handlerCount) == 0 && self.isValid)
{
SYPHONLOG(@"De-registering for frame updates");
SyphonMessageSender *sender = [[SyphonMessageSender alloc] initForName:[self.serverDescription objectForKey:SyphonServerDescriptionUUIDKey]
protocol:SyphonMessagingProtocolCFMessage
invalidationHandler:nil];
if (sender == nil)
{
SYPHONLOG(@"Failed to create connection to server with uuid:%@", [self.serverDescription objectForKey:SyphonServerDescriptionUUIDKey]);
[self endConnectionHavingLock:NO];
}
[sender send:_myUUID ofType:SyphonMessageTypeRemoveClientForFrames];
[sender release];
}
}
- (NSString*) description
{
OSSpinLockLock(&_lock);
NSDictionary *description = [_serverDescription retain];
OSSpinLockUnlock(&_lock);
NSString *result = [NSString stringWithFormat:@"Server UUID: %@, Server Name: %@, Host Application: %@",
[description objectForKey:SyphonServerDescriptionUUIDKey],
[description objectForKey:SyphonServerDescriptionNameKey],
[description objectForKey:SyphonServerDescriptionAppNameKey], nil];
[description release];
return result;
}
- (NSDictionary *)serverDescription
{
OSSpinLockLock(&_lock);
NSDictionary *description = [_serverDescription retain];
OSSpinLockUnlock(&_lock);
NSDictionary *result = [NSDictionary dictionaryWithDictionary:description];
[description release];
return result;
}
- (void)setServerName:(NSString *)name
{
if (name)
{
OSSpinLockLock(&_lock);
[_serverDescription setObject:name forKey:SyphonServerDescriptionNameKey];
OSSpinLockUnlock(&_lock);
}
}
- (void)publishNewFrame
{
// This could be dispatch_async WHEN we coalesce incoming messages
// Just now it's sync so a server can't flood a client (at the cost of blocking servers)
dispatch_sync(_frameQueue, ^{
for (id <SyphonFrameReceiving> obj in _frameClients) {
[obj receiveNewFrame];
}
});
}
- (IOSurfaceRef)surfaceHavingLock
{
if (!_surface)
{
// WHOA - This causes a retain.
_surface = IOSurfaceLookup(_surfaceID);
}
return _surface;
}
- (void)setSurfaceID:(IOSurfaceID)surfaceID
{
SYPHONLOG(@"Updating ID");
OSSpinLockLock(&_lock);
_surfaceID = surfaceID;
_frameID++; // new surface means a new frame
if (_surface)
{
CFRelease(_surface);
_surface = NULL;
[_frames removeAllObjects];
}
OSSpinLockUnlock(&_lock);
}
- (void)updateSurface:(NSDictionary *)description
{
// assign our new image formats.
NSNumber *internalFormat = [description valueForKey:SyphonServerIOSurfaceInternalFormatKey];
NSNumber *format = [description valueForKey:SyphonServerIOSurfaceFormatKey];
NSNumber *type = [description valueForKey:SyphonServerIOSurfaceTypeKey];
NSNumber *surfaceID = [description valueForKey:SyphonServerIOSurfaceIDKey];
if(internalFormat && format && type) // it's OK if surfaceID is missing (might be getting these before a surface has been created)
{
SYPHONLOG(@"Updating surface");
OSSpinLockLock(&_lock);
_internalFormat = [internalFormat unsignedIntValue];
_format = [format unsignedIntValue];
_type = [type unsignedIntValue];
_surfaceID = [surfaceID unsignedIntValue];
if (_surface)
{
CFRelease(_surface);
_surface = NULL;
[_frames removeAllObjects];
}
OSSpinLockUnlock(&_lock);
}
}
- (SyphonImage *)newFrameForContext:(CGLContextObj)context
{
SyphonImage *result;
OSSpinLockLock(&_lock);
result = NSMapGet(_frames, context);
if (result)
{
[result retain];
}
else
{
result = [[SyphonIOSurfaceImage alloc] initWithSurface:[self surfaceHavingLock] forContext:context internalFormat:_internalFormat format:_format type:_type];
NSMapInsertKnownAbsent(_frames, context, result);
}
OSSpinLockUnlock(&_lock);
return result;
}
- (NSUInteger)frameID
{
NSUInteger result;
OSSpinLockLock(&_lock);
IOSurfaceRef surface = [self surfaceHavingLock];
if (surface)
{
uint32_t seed = IOSurfaceGetSeed(surface);
if (_lastSeed != seed)
{
_frameID++;
_lastSeed = seed;
}
}
result = _frameID;
OSSpinLockUnlock(&_lock);
return result;
}
@end