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