[iphone] now decoders need to be injected into ZXingWidgetController to enhance perfo...
[zxing.git] / iphone / ZXingWidget / Classes / Decoder.mm
1 //
2 //  Decoder.m
3 //  ZXing
4 //
5 //  Created by Christian Brunschen on 31/03/2008.
6 //
7 /*
8  * Copyright 2008 ZXing authors
9  *
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  *
14  *      http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  */
22
23 #import "Decoder.h"
24 #import "TwoDDecoderResult.h"
25 #import "FormatReader.h"
26
27 #include <zxing/BinaryBitmap.h>
28 #include <zxing/ReaderException.h>
29 #include <zxing/common/IllegalArgumentException.h>
30 #include <zxing/common/GlobalHistogramBinarizer.h>
31 #include "GrayBytesMonochromeBitmapSource.h"
32
33 using namespace zxing;
34
35 @implementation Decoder
36
37 @synthesize image;
38 @synthesize cropRect;
39 @synthesize subsetImage;
40 @synthesize subsetData;
41 @synthesize subsetWidth;
42 @synthesize subsetHeight;
43 @synthesize subsetBytesPerRow;
44 @synthesize delegate;
45 @synthesize operationQueue;
46 @synthesize readers;
47
48
49 - (id)init {
50   if (self = [super init]) {
51     NSOperationQueue *opQueue = [[NSOperationQueue alloc] init];
52     self.operationQueue = opQueue;
53     [opQueue release];
54   }
55   return self;
56 }
57 - (void)willDecodeImage {
58   if ([self.delegate respondsToSelector:@selector(decoder:willDecodeImage:usingSubset:)]) {
59     [self.delegate decoder:self willDecodeImage:self.image usingSubset:self.subsetImage];
60   }
61 }
62
63 - (void)progressDecodingImage:(NSString *)progress {
64   if ([self.delegate respondsToSelector:@selector(decoder:decodingImage:usingSubset:progress:)]) {
65     [self.delegate decoder:self decodingImage:self.image usingSubset:self.subsetImage progress:progress];
66   }
67 }
68
69 - (void)didDecodeImage:(TwoDDecoderResult *)result {
70
71   if ([self.delegate respondsToSelector:@selector(decoder:didDecodeImage:usingSubset:withResult:)]) {
72     [self.delegate decoder:self didDecodeImage:self.image usingSubset:self.subsetImage withResult:result];
73   }
74         
75   [result release];
76 }
77
78 - (void)failedToDecodeImage:(NSString *)reason {
79
80   if ([self.delegate respondsToSelector:@selector(decoder:failedToDecodeImage:usingSubset:reason:)]) {
81     [self.delegate decoder:self failedToDecodeImage:self.image usingSubset:self.subsetImage reason:reason];
82   }
83 }
84
85 #define SUBSET_SIZE 320.0
86 - (void) prepareSubset {
87   CGSize size = [image size];
88 #ifdef DEBUG
89   NSLog(@"decoding: image is (%.1f x %.1f), cropRect is (%.1f,%.1f)x(%.1f,%.1f)", size.width, size.height,
90       cropRect.origin.x, cropRect.origin.y, cropRect.size.width, cropRect.size.height);
91 #endif
92   float scale = fminf(1.0f, fmaxf(SUBSET_SIZE / cropRect.size.width, SUBSET_SIZE / cropRect.size.height));
93   CGPoint offset = CGPointMake(-cropRect.origin.x, -cropRect.origin.y);
94 #ifdef DEBUG
95   NSLog(@"  offset = (%.1f, %.1f), scale = %.3f", offset.x, offset.y, scale);
96 #endif
97   
98   subsetWidth = cropRect.size.width * scale;
99   subsetHeight = cropRect.size.height * scale;
100   
101   subsetBytesPerRow = ((subsetWidth + 0xf) >> 4) << 4;
102 #ifdef DEBUG
103   NSLog(@"decoding: image to decode is (%d x %d) (%d bytes/row)", subsetWidth, subsetHeight, subsetBytesPerRow);
104 #endif
105   
106   subsetData = (unsigned char *)malloc(subsetBytesPerRow * subsetHeight);
107 #ifdef DEBUG
108   NSLog(@"allocated %d bytes of memory", subsetBytesPerRow * subsetHeight);
109 #endif
110   
111   CGColorSpaceRef grayColorSpace = CGColorSpaceCreateDeviceGray();
112   
113   CGContextRef ctx = 
114   CGBitmapContextCreate(subsetData, subsetWidth, subsetHeight, 
115               8, subsetBytesPerRow, grayColorSpace, 
116               kCGImageAlphaNone);
117   CGColorSpaceRelease(grayColorSpace);
118   CGContextSetInterpolationQuality(ctx, kCGInterpolationNone);
119   CGContextSetAllowsAntialiasing(ctx, false);
120   // adjust the coordinate system
121   CGContextTranslateCTM(ctx, 0.0, subsetHeight);
122   CGContextScaleCTM(ctx, 1.0, -1.0);  
123   
124 #ifdef DEBUG
125   NSLog(@"created %dx%d bitmap context", subsetWidth, subsetHeight);
126 #endif
127   
128   UIGraphicsPushContext(ctx);
129   CGRect rect = CGRectMake(offset.x * scale, offset.y * scale, scale * size.width, scale * size.height);
130 #ifdef DEBUG
131   NSLog(@"rect for image = (%.1f,%.1f)x(%.1f,%.1f)", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
132 #endif
133   [image drawInRect:rect];
134   UIGraphicsPopContext();
135   
136 #ifdef DEBUG
137   NSLog(@"drew image into %d(%d)x%d  bitmap context", subsetWidth, subsetBytesPerRow, subsetHeight);
138 #endif
139   CGContextFlush(ctx);
140 #ifdef DEBUG
141   NSLog(@"flushed context");
142 #endif
143     
144   CGImageRef subsetImageRef = CGBitmapContextCreateImage(ctx);
145 #ifdef DEBUG
146   NSLog(@"created CGImage from context");
147 #endif
148   
149   self.subsetImage = [UIImage imageWithCGImage:subsetImageRef];
150   CGImageRelease(subsetImageRef);
151   
152   CGContextRelease(ctx);
153 #ifdef DEBUG
154   NSLog(@"released context");  
155 #endif
156 }  
157
158 - (void)decode:(id)arg {
159   NSAutoreleasePool* mainpool = [[NSAutoreleasePool alloc] init];
160   { 
161     //NSSet *formatReaders = [FormatReader formatReaders];
162     NSSet *formatReaders = self.readers;
163     Ref<LuminanceSource> source (new GrayBytesMonochromeBitmapSource(subsetData, subsetWidth, subsetHeight, subsetBytesPerRow));
164     Ref<Binarizer> binarizer (new GlobalHistogramBinarizer(source));
165     Ref<BinaryBitmap> grayImage (new BinaryBitmap(binarizer));
166 #ifdef DEBUG
167     NSLog(@"created GrayBytesMonochromeBitmapSource", subsetWidth, subsetHeight);
168     NSLog(@"grayImage count = %d", grayImage->count());
169 #endif
170     
171     TwoDDecoderResult *decoderResult = nil;
172     
173 #ifdef TRY_ROTATIONS
174     for (int i = 0; !decoderResult && i < 4; i++) {
175 #endif
176       for (FormatReader *reader in formatReaders) {
177         NSAutoreleasePool *secondarypool = [[NSAutoreleasePool alloc] init];
178         try {
179   #ifdef DEBUG
180           NSLog(@"decoding gray image");
181   #endif  
182           Ref<Result> result([reader decode:grayImage]);
183   #ifdef DEBUG
184           NSLog(@"gray image decoded");
185   #endif
186           
187           Ref<String> resultText(result->getText());
188           const char *cString = resultText->getText().c_str();
189           const std::vector<Ref<ResultPoint> > &resultPoints = result->getResultPoints();
190           NSMutableArray *points = 
191             [[NSMutableArray alloc ] initWithCapacity:resultPoints.size()];
192           
193           for (size_t i = 0; i < resultPoints.size(); i++) {
194             const Ref<ResultPoint> &rp = resultPoints[i];
195             CGPoint p = CGPointMake(rp->getX(), rp->getY());
196             [points addObject:[NSValue valueWithCGPoint:p]];
197           }
198           
199           NSString *resultString = [NSString stringWithCString:cString
200                                 encoding:NSUTF8StringEncoding];
201           
202           decoderResult = [[TwoDDecoderResult resultWithText:resultString
203                                                      points:points] retain];
204           [points release];
205         } catch (ReaderException &rex) {
206           NSLog(@"failed to decode, caught ReaderException '%s'",
207               rex.what());
208         } catch (IllegalArgumentException &iex) {
209           NSLog(@"failed to decode, caught IllegalArgumentException '%s'", 
210               iex.what());
211         } catch (...) {
212           NSLog(@"Caught unknown exception!");
213         }
214         [secondarypool release];
215       }
216       
217 #ifdef TRY_ROTATIONS
218       if (!decoderResult) {
219 #ifdef DEBUG
220         NSLog(@"rotating gray image");
221 #endif
222         grayImage = grayImage->rotateCounterClockwise();
223 #ifdef DEBUG
224         NSLog(@"gray image rotated");
225 #endif
226       }
227     }
228 #endif
229           
230         free(subsetData);
231         self.subsetData = NULL;
232           
233     if (decoderResult) {
234       [self performSelectorOnMainThread:@selector(didDecodeImage:)
235                    withObject:decoderResult
236                 waitUntilDone:NO];
237     } else {
238       [self performSelectorOnMainThread:@selector(failedToDecodeImage:)
239                    withObject:NSLocalizedString(@"Decoder BarcodeDetectionFailure", @"No barcode detected.")
240                 waitUntilDone:NO];
241     }
242   }
243   
244   
245 #ifdef DEBUG
246   NSLog(@"finished decoding.");
247 #endif
248   [mainpool release];
249 }
250
251 - (void) decodeImage:(UIImage *)i {
252   [self decodeImage:i cropRect:CGRectMake(0.0f, 0.0f, i.size.width, i.size.height)];
253 }
254
255
256 - (void) asyncDecodeImage {
257   [self prepareSubset];
258   [self willDecodeImage];
259   [self performSelectorOnMainThread:@selector(willDecodeImage) 
260                          withObject:nil 
261                       waitUntilDone:NO];
262   [self performSelectorOnMainThread:@selector(progressDecodingImage:)
263                          withObject:NSLocalizedString(@"Decoder MessageWhileDecoding", @"Decoding ...")
264                       waitUntilDone:NO];
265 /*  NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(decode:) object:nil];
266   [operationQueue addOperation:op];
267   [op release];*/
268   [self decode:nil];
269 }
270 - (void) decodeImage:(UIImage *)i cropRect:(CGRect)cr {
271   self.image = i;
272   self.cropRect = cr;
273   NSInvocationOperation *op = [[NSInvocationOperation  alloc] initWithTarget:self selector:@selector(asyncDecodeImage) object:nil];
274   [operationQueue addOperation:op];
275   [op release];
276 }
277
278 - (void) dealloc {
279
280   [image release];
281   [subsetImage release];
282   if (subsetData) free(subsetData);
283   [operationQueue release];
284   [readers release];
285   [super dealloc];
286 }
287
288 @end