ea7748b47d1a27214fc77619dc39fc99f87348a2
[zxing.git] / iphone / 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
46 - (void)willDecodeImage {
47   if ([self.delegate respondsToSelector:@selector(decoder:willDecodeImage:usingSubset:)]) {
48     [self.delegate decoder:self willDecodeImage:self.image usingSubset:self.subsetImage];
49   }
50 }
51
52 - (void)progressDecodingImage:(NSString *)progress {
53   if ([self.delegate respondsToSelector:@selector(decoder:decodingImage:usingSubset:progress:)]) {
54     [self.delegate decoder:self decodingImage:self.image usingSubset:self.subsetImage progress:progress];
55   }
56 }
57
58 - (void)didDecodeImage:(TwoDDecoderResult *)result {
59   if ([self.delegate respondsToSelector:@selector(decoder:didDecodeImage:usingSubset:withResult:)]) {
60     [self.delegate decoder:self didDecodeImage:self.image usingSubset:self.subsetImage withResult:result];
61   }
62 }
63
64 - (void)failedToDecodeImage:(NSString *)reason {
65   if ([self.delegate respondsToSelector:@selector(decoder:failedToDecodeImage:usingSubset:reason:)]) {
66     [self.delegate decoder:self failedToDecodeImage:self.image usingSubset:self.subsetImage reason:reason];
67   }
68 }
69
70 #define SUBSET_SIZE 320.0
71 - (void) prepareSubset {
72   CGSize size = [image size];
73 #ifdef DEBUG
74   NSLog(@"decoding: image is (%.1f x %.1f), cropRect is (%.1f,%.1f)x(%.1f,%.1f)", size.width, size.height,
75       cropRect.origin.x, cropRect.origin.y, cropRect.size.width, cropRect.size.height);
76 #endif
77   float scale = fminf(1.0f, fmaxf(SUBSET_SIZE / cropRect.size.width, SUBSET_SIZE / cropRect.size.height));
78   CGPoint offset = CGPointMake(-cropRect.origin.x, -cropRect.origin.y);
79 #ifdef DEBUG
80   NSLog(@"  offset = (%.1f, %.1f), scale = %.3f", offset.x, offset.y, scale);
81 #endif
82   
83   subsetWidth = cropRect.size.width * scale;
84   subsetHeight = cropRect.size.height * scale;
85   
86   subsetBytesPerRow = ((subsetWidth + 0xf) >> 4) << 4;
87 #ifdef DEBUG
88   NSLog(@"decoding: image to decode is (%d x %d) (%d bytes/row)", subsetWidth, subsetHeight, subsetBytesPerRow);
89 #endif
90   
91   subsetData = (unsigned char *)malloc(subsetBytesPerRow * subsetHeight);
92 #ifdef DEBUG
93   NSLog(@"allocated %d bytes of memory", subsetBytesPerRow * subsetHeight);
94 #endif
95   
96   CGColorSpaceRef grayColorSpace = CGColorSpaceCreateDeviceGray();
97   
98   CGContextRef ctx = 
99   CGBitmapContextCreate(subsetData, subsetWidth, subsetHeight, 
100               8, subsetBytesPerRow, grayColorSpace, 
101               kCGImageAlphaNone);
102   CGColorSpaceRelease(grayColorSpace);
103   CGContextSetInterpolationQuality(ctx, kCGInterpolationNone);
104   CGContextSetAllowsAntialiasing(ctx, false);
105   // adjust the coordinate system
106   CGContextTranslateCTM(ctx, 0.0, subsetHeight);
107   CGContextScaleCTM(ctx, 1.0, -1.0);  
108   
109 #ifdef DEBUG
110   NSLog(@"created %dx%d bitmap context", subsetWidth, subsetHeight);
111 #endif
112   
113   UIGraphicsPushContext(ctx);
114   CGRect rect = CGRectMake(offset.x * scale, offset.y * scale, scale * size.width, scale * size.height);
115 #ifdef DEBUG
116   NSLog(@"rect for image = (%.1f,%.1f)x(%.1f,%.1f)", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
117 #endif
118   [image drawInRect:rect];
119   UIGraphicsPopContext();
120   
121 #ifdef DEBUG
122   NSLog(@"drew image into %d(%d)x%d  bitmap context", subsetWidth, subsetBytesPerRow, subsetHeight);
123 #endif
124   CGContextFlush(ctx);
125 #ifdef DEBUG
126   NSLog(@"flushed context");
127 #endif
128     
129   CGImageRef subsetImageRef = CGBitmapContextCreateImage(ctx);
130 #ifdef DEBUG
131   NSLog(@"created CGImage from context");
132 #endif
133   
134   self.subsetImage = [UIImage imageWithCGImage:subsetImageRef];
135   CGImageRelease(subsetImageRef);
136   
137   CGContextRelease(ctx);
138 #ifdef DEBUG
139   NSLog(@"released context");  
140 #endif
141 }  
142
143 - (void)decode:(id)arg {
144   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
145   { 
146
147     NSSet *formatReaders = [FormatReader formatReaders];
148     
149     Ref<LuminanceSource> source (new GrayBytesMonochromeBitmapSource(subsetData, subsetWidth, subsetHeight, subsetBytesPerRow));
150     
151     Ref<Binarizer> binarizer (new GlobalHistogramBinarizer(source));
152     Ref<BinaryBitmap> grayImage (new BinaryBitmap(binarizer));
153 #ifdef DEBUG
154     NSLog(@"created GrayBytesMonochromeBitmapSource", subsetWidth, subsetHeight);
155     NSLog(@"grayImage count = %d", grayImage->count());
156 #endif
157     
158     TwoDDecoderResult *decoderResult = nil;
159     
160 #ifdef TRY_ROTATIONS
161     for (int i = 0; !decoderResult && i < 4; i++) {
162 #endif
163       for (FormatReader *reader in formatReaders) {
164         try {
165   #ifdef DEBUG
166           NSLog(@"decoding gray image");
167   #endif
168           Ref<Result> result([reader decode:grayImage]);
169   #ifdef DEBUG
170           NSLog(@"gray image decoded");
171   #endif
172           
173           Ref<String> resultText(result->getText());
174           const char *cString = resultText->getText().c_str();
175           const std::vector<Ref<ResultPoint> > &resultPoints = result->getResultPoints();
176           NSMutableArray *points = 
177             [NSMutableArray arrayWithCapacity:resultPoints.size()];
178           
179           for (size_t i = 0; i < resultPoints.size(); i++) {
180             const Ref<ResultPoint> &rp = resultPoints[i];
181             CGPoint p = CGPointMake(rp->getX(), rp->getY());
182             [points addObject:[NSValue valueWithCGPoint:p]];
183           }
184           
185           NSString *resultString = [NSString stringWithCString:cString
186                                 encoding:NSUTF8StringEncoding];
187           
188           decoderResult = [TwoDDecoderResult resultWithText:resultString
189                                                      points:points];
190         } catch (ReaderException &rex) {
191           NSLog(@"failed to decode, caught ReaderException '%s'",
192               rex.what());
193         } catch (IllegalArgumentException &iex) {
194           NSLog(@"failed to decode, caught IllegalArgumentException '%s'", 
195               iex.what());
196         } catch (...) {
197           NSLog(@"Caught unknown exception!");
198         }
199       }
200       
201 #ifdef TRY_ROTATIONS
202       if (!decoderResult) {
203 #ifdef DEBUG
204         NSLog(@"rotating gray image");
205 #endif
206         grayImage = grayImage->rotateCounterClockwise();
207 #ifdef DEBUG
208         NSLog(@"gray image rotated");
209 #endif
210       }
211     }
212 #endif
213     
214     if (decoderResult) {
215       [self performSelectorOnMainThread:@selector(didDecodeImage:)
216                    withObject:decoderResult
217                 waitUntilDone:NO];
218     } else {
219       [self performSelectorOnMainThread:@selector(failedToDecodeImage:)
220                    withObject:NSLocalizedString(@"Decoder BarcodeDetectionFailure", @"No barcode detected.")
221                 waitUntilDone:NO];
222     }
223     
224     free(subsetData);
225     self.subsetData = NULL;
226   }
227   [pool drain];
228 #ifdef DEBUG
229   NSLog(@"finished decoding.");
230 #endif
231   
232   // if this is not the main thread, then we end it
233   if (![NSThread isMainThread]) {
234     [NSThread exit];
235   }
236 }
237
238 - (void) decodeImage:(UIImage *)i {
239   [self decodeImage:i cropRect:CGRectMake(0.0f, 0.0f, image.size.width, image.size.height)];
240 }
241
242 - (void) decodeImage:(UIImage *)i cropRect:(CGRect)cr {
243   self.image = i;
244   self.cropRect = cr;
245   
246   [self prepareSubset];
247   [self willDecodeImage];
248   [self performSelectorOnMainThread:@selector(progressDecodingImage:)
249                withObject:NSLocalizedString(@"Decoder MessageWhileDecoding", @"Decoding ...")
250             waitUntilDone:NO];  
251   
252   [NSThread detachNewThreadSelector:@selector(decode:) 
253                toTarget:self 
254                withObject:nil];
255 }
256
257 - (void) dealloc {
258   [image release];
259   [subsetImage release];
260   if (subsetData) free(subsetData);
261   [super dealloc];
262 }
263
264 @end