/
SCFilter.m
550 lines (418 loc) · 16.3 KB
/
SCFilter.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
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
//
// SCFilter.m
// CoreImageShop
//
// Created by Simon CORSIN on 16/05/14.
//
//
#import "SCFilter.h"
@interface SCFilter() {
NSMutableDictionary *_unwrappedValues;
NSMutableArray *_subFilters;
NSMutableArray *_animations;
}
@property (strong, nonatomic) CIImage *overlayImage;
@end
@implementation SCFilter
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [self init];
if (self) {
_CIFilter = [aDecoder decodeObjectForKey:@"CoreImageFilter"];
self.enabled = [aDecoder decodeBoolForKey:@"Enabled"];
if ([aDecoder containsValueForKey:@"VectorsData"]) {
NSArray *vectors = [aDecoder decodeObjectForKey:@"VectorsData"];
for (NSArray *vectorData in vectors) {
CGFloat *vectorValue = malloc(sizeof(CGFloat) * (vectorData.count - 1));
if (vectorData != nil) {
for (int i = 1; i < vectorData.count; i++) {
NSNumber *value = [vectorData objectAtIndex:i];
vectorValue[i - 1] = (CGFloat)value.doubleValue;
}
NSString *key = vectorData.firstObject;
[_CIFilter setValue:[CIVector vectorWithValues:vectorValue count:vectorData.count - 1] forKey:key];
free(vectorValue);
}
}
}
if ([aDecoder containsValueForKey:@"UnwrappedValues"]) {
NSDictionary *unwrappedValues = [aDecoder decodeObjectForKey:@"UnwrappedValues"];
for (NSString *key in unwrappedValues) {
[self setParameterValue:[unwrappedValues objectForKey:key] forKey:key];
}
}
if ([aDecoder containsValueForKey:@"SubFilters"]) {
_subFilters = [[aDecoder decodeObjectForKey:@"SubFilters"] mutableCopy];
}
if ([aDecoder containsValueForKey:@"Name"]) {
_name = [aDecoder decodeObjectForKey:@"Name"];
} else {
_name = [_CIFilter.attributes objectForKey:kCIAttributeFilterName];
}
if ([aDecoder containsValueForKey:@"Animations"]) {
_animations = [[aDecoder decodeObjectForKey:@"Animations"] mutableCopy];
}
}
return self;
}
- (instancetype)init {
self = [super init];
if (self) {
_unwrappedValues = [NSMutableDictionary new];
_subFilters = [NSMutableArray new];
_animations = [NSMutableArray new];
self.enabled = YES;
}
return self;
}
- (instancetype)initWithCIFilter:(CIFilter *)filter {
self = [self init];
if (self) {
_name = [filter.attributes objectForKey:kCIAttributeFilterDisplayName];
_CIFilter = filter;
}
return self;
}
- (id)copyWithZone:(NSZone *)zone {
SCFilter *filter = [SCFilter emptyFilter];
if (filter != nil) {
filter->_name = [_name copy];
filter->_CIFilter = [_CIFilter copy];
filter->_unwrappedValues = [_unwrappedValues mutableCopy];
filter->_subFilters = [_subFilters mutableCopy];
filter->_animations = [_animations mutableCopy];
}
return filter;
}
- (id)_unwrappedValue:(id)value forKey:(NSString *)key {
id unwrappedValue = [_unwrappedValues objectForKey:key];
return unwrappedValue == nil ? value : unwrappedValue;
}
- (id)_wrappedValue:(id)value forKey:(NSString *)key {
if (value == nil) {
[_unwrappedValues removeObjectForKey:key];
} else {
if ([key isEqualToString:@"inputCubeData"]) {
if ([value isKindOfClass:[NSData class]]) {
NSData *data = value;
CGDataProviderRef source = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
if (source == nil) {
NSLog(@"Unable to get source provider for key %@", key);
return nil;
}
CGImageRef image = nil;
if ([SCFilter data:data hasMagic:MagicPNG]) {
image = CGImageCreateWithPNGDataProvider(source, nil, NO, kCGRenderingIntentDefault);
} else if ([SCFilter data:data hasMagic:MagicJPG]) {
image = CGImageCreateWithJPEGDataProvider(source, nil, NO, kCGRenderingIntentDefault);
} else {
NSLog(@"Input data for key %@ must be either representing a PNG or a JPG file", key);
CGDataProviderRelease(source);
return nil;
}
if (image == nil) {
NSLog(@"Unable to create image for key %@ from input data", key);
CGDataProviderRelease(source);
return nil;
}
CGDataProviderRelease(source);
NSInteger dimension = [[_CIFilter valueForKey:@"inputCubeDimension"] integerValue];
[_unwrappedValues setObject:data forKey:key];
value = [SCFilter colorCubeDataWithCGImage:image dimension:dimension];
CGImageRelease(image);
} else {
NSLog(@"Value for key %@ must be of type NSData (got type: %@)", key, [value class]);
return nil;
}
}
}
return value;
}
- (void)_didChangeParameter:(NSString *)key {
if ([key isEqualToString:@"inputCubeDimension"]) {
NSData *inputCubeData = [_unwrappedValues objectForKey:@"inputCubeData"];
if (inputCubeData != nil) {
[self setParameterValue:inputCubeData forKey:@"inputCubeData"];
}
}
}
- (id)parameterValueForKey:(NSString *)key {
return [self _unwrappedValue:[_CIFilter valueForKey:key] forKey:key];
}
- (void)setParameterValue:(id)value forKey:(NSString *)key {
value = [self _wrappedValue:value forKey:key];
[_CIFilter setValue:value forKey:key];
[self _didChangeParameter:key];
id<SCFilterDelegate> delegate = self.delegate;
if ([delegate respondsToSelector:@selector(filter:didChangeParameter:)]) {
[delegate filter:self didChangeParameter:key];
}
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
CIFilter *copiedFilter = _CIFilter.copy;
for (NSString *key in _unwrappedValues) {
[copiedFilter setValue:nil forKey:key];
}
if (copiedFilter != nil) {
[aCoder encodeObject:copiedFilter forKey:@"CoreImageFilter"];
}
[aCoder encodeBool:self.enabled forKey:@"Enabled"];
[aCoder encodeObject:_unwrappedValues forKey:@"UnwrappedValues"];
NSMutableArray *vectors = [NSMutableArray new];
for (NSString *key in _CIFilter.inputKeys) {
id value = [_CIFilter valueForKey:key];
if ([value isKindOfClass:[CIVector class]]) {
CIVector *vector = value;
NSMutableArray *vectorData = [NSMutableArray new];
[vectorData addObject:key];
for (int i = 0; i < vector.count; i++) {
CGFloat value = [vector valueAtIndex:i];
[vectorData addObject:[NSNumber numberWithDouble:(double)value]];
}
[vectors addObject:vectorData];
}
}
[aCoder encodeObject:vectors forKey:@"VectorsData"];
[aCoder encodeObject:_subFilters forKey:@"SubFilters"];
[aCoder encodeObject:_name forKey:@"Name"];
[aCoder encodeObject:_animations forKey:@"Animations"];
}
- (void)resetToDefaults {
[_CIFilter setDefaults];
[_unwrappedValues removeAllObjects];
for (SCFilter *subFilter in _subFilters) {
[subFilter resetToDefaults];
}
id<SCFilterDelegate> delegate = self.delegate;
if ([delegate respondsToSelector:@selector(filterDidResetToDefaults:)]) {
[delegate filterDidResetToDefaults:self];
}
}
- (void)addSubFilter:(SCFilter *)subFilter {
[_subFilters addObject:subFilter];
}
- (void)removeSubFilter:(SCFilter *)subFilter {
[_subFilters removeObject:subFilter];
}
- (void)insertSubFilter:(SCFilter *)subFilter atIndex:(NSInteger)index {
[_subFilters insertObject:subFilter atIndex:index];
}
- (void)removeSubFilterAtIndex:(NSInteger)index {
[_subFilters removeObjectAtIndex:index];
}
- (SCFilterAnimation *)addAnimationForParameterKey:(NSString *)key startValue:(id)startValue endValue:(id)endValue startTime:(CFTimeInterval)startTime duration:(CFTimeInterval)duration {
SCFilterAnimation *animation = [SCFilterAnimation filterAnimationForParameterKey:key startValue:startValue endValue:endValue startTime:startTime duration:duration];
[self addAnimation:animation];
return animation;
}
- (void)addAnimation:(SCFilterAnimation *)animation {
[_animations addObject:animation];
}
- (void)removeAnimation:(SCFilterAnimation *)animation {
[_animations removeObject:animation];
}
- (void)removeAllAnimations {
[_animations removeAllObjects];
}
- (NSArray *)subFilters {
return _subFilters;
}
- (CIImage *)imageByProcessingImage:(CIImage *)image {
return [self imageByProcessingImage:image atTime:0];
}
- (CIImage *)imageByProcessingImage:(CIImage *)image atTime:(CFTimeInterval)time {
if (!self.enabled) {
return image;
}
id<SCFilterDelegate> delegate = self.delegate;
if ([delegate respondsToSelector:@selector(filter:willProcessImage:atTime:)]) {
[delegate filter:self willProcessImage:image atTime:time];
}
for (SCFilter *filter in _subFilters) {
image = [filter imageByProcessingImage:image atTime:time];
}
for (SCFilterAnimation *animation in _animations) {
if ([animation hasValueAtTime:time]) {
id value = [animation valueAtTime:time];
[self setParameterValue:value forKey:animation.key];
}
}
CIImage *overlayImage = _overlayImage;
if (overlayImage != nil) {
image = [overlayImage imageByCompositingOverImage:image];
}
CIFilter *ciFilter = _CIFilter;
if (ciFilter == nil) {
return image;
}
[ciFilter setValue:image forKey:kCIInputImageKey];
return [ciFilter valueForKey:kCIOutputImageKey];
}
- (void)writeToFile:(NSURL *)fileUrl error:(NSError *__autoreleasing *)error {
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self];
[data writeToURL:fileUrl options:NSDataWritingAtomic error:error];
}
- (BOOL)isEmpty {
BOOL isEmpty = YES;
if (_CIFilter != nil || _overlayImage != nil) {
return NO;
}
for (SCFilter *filter in _subFilters) {
isEmpty &= filter.isEmpty;
}
return isEmpty;
}
- (NSArray *)animations {
return _animations;
}
+ (SCFilter *)emptyFilter {
return [SCFilter filterWithCIFilter:nil];
}
+ (SCFilter *)filterWithAffineTransform:(CGAffineTransform)affineTransform {
CIFilter *filter = [CIFilter filterWithName:@"CIAffineTransform"];
[filter setValue:[NSValue valueWithBytes:&affineTransform objCType:@encode(CGAffineTransform)] forKey:@"inputTransform"];
return [SCFilter filterWithCIFilter:filter];
}
+ (SCFilter *)filterWithCIFilter:(CIFilter *)filterDescription {
return [[SCFilter alloc] initWithCIFilter:filterDescription];
}
+ (SCFilter *)filterWithCIFilterName:(NSString *)name {
CIFilter *coreImageFilter = [CIFilter filterWithName:name];
[coreImageFilter setDefaults];
return coreImageFilter != nil ? [SCFilter filterWithCIFilter:coreImageFilter] : nil;
}
+ (SCFilter *)filterWithData:(NSData *)data error:(NSError *__autoreleasing *)error {
id obj = nil;
@try {
obj = [NSKeyedUnarchiver unarchiveObjectWithData:data];
} @catch (NSException *exception) {
if (error != nil) {
*error = [NSError errorWithDomain:@"SCFilterGroup" code:200 userInfo:@{
NSLocalizedDescriptionKey : exception.reason
}];
return nil;
}
}
if (![obj isKindOfClass:[SCFilter class]]) {
obj = nil;
if (error != nil) {
*error = [NSError errorWithDomain:@"FilterDomain" code:200 userInfo:@{
NSLocalizedDescriptionKey : @"Invalid serialized class type"
}];
}
}
return obj;
}
+ (SCFilter *)filterWithData:(NSData *)data {
return [SCFilter filterWithData:data error:nil];
}
+ (SCFilter *)filterWithContentsOfURL:(NSURL *)url {
NSData *data = [NSData dataWithContentsOfURL:url];
if (data != nil) {
return [SCFilter filterWithData:data];
}
return nil;
}
+ (SCFilter *)filterWithFilters:(NSArray *)filters {
SCFilter *filter = [SCFilter emptyFilter];
for (SCFilter *subFilter in filters) {
[filter addSubFilter:subFilter];
}
return filter;
}
+ (SCFilter *)filterWithCIImage:(CIImage *)image {
SCFilter *filter = [SCFilter emptyFilter];
filter.overlayImage = image;
return filter;
}
static UInt32 MagicPNG = 0x474e5089;
static UInt32 MagicJPG = 0xe0ffd8ff;
+ (BOOL)data:(NSData *)data hasMagic:(UInt32)magic {
if (data.length > sizeof(magic)) {
const UInt32 *bytes = data.bytes;
UInt32 actualMagic = *bytes;
return actualMagic == magic;
}
return NO;
}
/////
// These two functions were taken from https://github.com/NghiaTranUIT/FeSlideFilter
//
+ (NSData *)colorCubeDataWithCGImage:(CGImageRef )image dimension:(NSInteger)n {
if (n == 0) {
return nil;
}
NSInteger width = CGImageGetWidth(image);
NSInteger height = CGImageGetHeight(image);
NSInteger rowNum = height / n;
NSInteger columnNum = width / n;
if ((width % n != 0) || (height % n != 0) || (rowNum * columnNum != n)) {
return nil;
}
UInt8 *bitmap = [self createRGBABitmapFromImage:image];
if (bitmap == nil) {
return nil;
}
const int colorChannels = 4;
NSInteger size = n * n * n * sizeof(float) * colorChannels;
float *data = malloc(size);
if (data == nil) {
free(bitmap);
return nil;
}
UInt8 *bitmapPtr = bitmap;
int z = 0;
for (int row = 0; row < rowNum; row++) {
for (int y = 0; y < n; y++) {
int tmp = z;
for (int col = 0; col < columnNum; col++) {
for (int x = 0; x < n; x++) {
UInt8 r = *bitmapPtr++;
UInt8 g = *bitmapPtr++;
UInt8 b = *bitmapPtr++;
UInt8 a = *bitmapPtr++;
NSInteger dataOffset = (z * n * n + y * n + x) * 4;
data[dataOffset] = r / 255.0;
data[dataOffset + 1] = g / 255.0;
data[dataOffset + 2] = b / 255.0;
data[dataOffset + 3] = a / 255.0;
}
z++;
}
z = tmp;
}
z += columnNum;
}
free(bitmap);
return [NSData dataWithBytesNoCopy:data length:size freeWhenDone:YES];
}
+ (unsigned char *)createRGBABitmapFromImage:(CGImageRef)image {
size_t width = CGImageGetWidth(image);
size_t height = CGImageGetHeight(image);
NSInteger bytesPerRow = (width * 4);
NSInteger bitmapSize = (bytesPerRow * height);
unsigned char *bitmap = malloc(bitmapSize);
if (bitmap == nil) {
return nil;
}
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
if (colorSpace == nil) {
free(bitmap);
return nil;
}
CGContextRef context = CGBitmapContextCreate(bitmap,
width,
height,
8,
bytesPerRow,
colorSpace,
(CGBitmapInfo)kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorSpace);
if (context == nil) {
free(bitmap);
return nil;
}
CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
CGContextRelease(context);
return bitmap;
}
@end