summaryrefslogtreecommitdiffstats
path: root/iphone/ZBarReaderViewImpl_Capture.m
blob: dd5a696ec205ae3f67a27b68da7216feeec2fa08 (plain)
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
//------------------------------------------------------------------------
//  Copyright 2010 (c) Jeff Brown <spadix@users.sourceforge.net>
//
//  This file is part of the ZBar Bar Code Reader.
//
//  The ZBar Bar Code Reader is free software; you can redistribute it
//  and/or modify it under the terms of the GNU Lesser Public License as
//  published by the Free Software Foundation; either version 2.1 of
//  the License, or (at your option) any later version.
//
//  The ZBar Bar Code Reader is distributed in the hope that it will be
//  useful, but WITHOUT ANY WARRANTY; without even the implied warranty
//  of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser Public License for more details.
//
//  You should have received a copy of the GNU Lesser Public License
//  along with the ZBar Bar Code Reader; if not, write to the Free
//  Software Foundation, Inc., 51 Franklin St, Fifth Floor,
//  Boston, MA  02110-1301  USA
//
//  http://sourceforge.net/projects/zbar
//------------------------------------------------------------------------

#import <AVFoundation/AVFoundation.h>
#import <CoreMedia/CoreMedia.h>
#import <CoreVideo/CoreVideo.h>
#import <ZBarSDK/ZBarReaderView.h>
#import <ZBarSDK/ZBarCaptureReader.h>

#define MODULE ZBarReaderView
#import "debug.h"

// protected APIs
@interface ZBarReaderView()
- (void) _initWithImageScanner: (ZBarImageScanner*) _scanner;
- (void) initSubviews;
- (void) updateCrop;
- (void) setImageSize: (CGSize) size;
- (void) didTrackSymbols: (ZBarSymbolSet*) syms;
@end

@interface ZBarReaderViewImpl
    : ZBarReaderView
{
    AVCaptureSession *session;
    AVCaptureDevice *device;
    AVCaptureInput *input;
}

@end

@implementation ZBarReaderViewImpl

@synthesize device, session;

- (void) _initWithImageScanner: (ZBarImageScanner*) scanner
{
    [super _initWithImageScanner: scanner];

    session = [AVCaptureSession new];
    NSNotificationCenter *notify =
        [NSNotificationCenter defaultCenter];
    [notify addObserver: self
            selector: @selector(onVideoError:)
            name: AVCaptureSessionRuntimeErrorNotification
            object: session];
    [notify addObserver: self
            selector: @selector(onVideoStart:)
            name: AVCaptureSessionDidStartRunningNotification
            object: session];
    [notify addObserver: self
            selector: @selector(onVideoStop:)
            name: AVCaptureSessionDidStopRunningNotification
            object: session];
    [notify addObserver: self
            selector: @selector(onVideoStop:)
            name: AVCaptureSessionWasInterruptedNotification
            object: session];
    [notify addObserver: self
            selector: @selector(onVideoStart:)
            name: AVCaptureSessionInterruptionEndedNotification
            object: session];

    self.device = [AVCaptureDevice
                      defaultDeviceWithMediaType: AVMediaTypeVideo];

    captureReader = [[ZBarCaptureReader alloc]
                        initWithImageScanner: scanner];
    captureReader.captureDelegate = (id<ZBarCaptureDelegate>)self;
    [session addOutput: captureReader.captureOutput];

    if([session canSetSessionPreset: AVCaptureSessionPreset640x480])
        session.sessionPreset = AVCaptureSessionPreset640x480;

    [captureReader addObserver: self
                   forKeyPath: @"size"
                   options: 0
                   context: NULL];

    [self initSubviews];
}

- (void) initSubviews
{
    AVCaptureVideoPreviewLayer *videoPreview =
        [[AVCaptureVideoPreviewLayer
             layerWithSession: session]
            retain];
    preview = videoPreview;
    CGRect bounds = self.bounds;
    bounds.origin = CGPointZero;
    preview.bounds = bounds;
    preview.position = CGPointMake(bounds.size.width / 2,
                                   bounds.size.height / 2);
    videoPreview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.layer addSublayer: preview];

    [super initSubviews];
}

- (void) dealloc
{
    [[NSNotificationCenter defaultCenter]
        removeObserver: self];
    if(showsFPS) {
        @try {
            [captureReader removeObserver: self
                           forKeyPath: @"framesPerSecond"];
        }
        @catch(...) { }
    }
    @try {
        [captureReader removeObserver: self
                       forKeyPath: @"size"];
    }
    @catch(...) { }
    captureReader.captureDelegate = nil;
    [captureReader release];
    captureReader = nil;
    [device release];
    device = nil;
    [input release];
    input = nil;
    [session release];
    session = nil;
    [super dealloc];
}

- (void) updateCrop
{
    [super updateCrop];
    captureReader.scanCrop = effectiveCrop;
}

- (ZBarImageScanner*) scanner
{
    return(captureReader.scanner);
}

- (void) setDevice: (AVCaptureDevice*) newdev
{
    id olddev = device;
    AVCaptureInput *oldinput = input;
    assert(!olddev == !oldinput);

    NSError *error = nil;
    device = [newdev retain];
    if(device) {
        assert([device hasMediaType: AVMediaTypeVideo]);
        input = [[AVCaptureDeviceInput alloc]
                    initWithDevice: newdev
                    error: &error];
        assert(input);
    }
    else
        input = nil;

    [session beginConfiguration];
    if(oldinput)
        [session removeInput: oldinput];
    if(input)
        [session addInput: input];
    [session commitConfiguration];

    [olddev release];
    [oldinput release];
}

- (BOOL) enableCache
{
    return(captureReader.enableCache);
}

- (void) setEnableCache: (BOOL) enable
{
    captureReader.enableCache = enable;
}

- (void) setTorchMode: (NSInteger) mode
{
    [super setTorchMode: mode];
    if(running && [device isTorchModeSupported: mode])
        @try {
            device.torchMode = mode;
        }
        @catch(...) { }
}

- (void) setShowsFPS: (BOOL) show
{
    [super setShowsFPS: show];
    @try {
        if(show)
            [captureReader addObserver: self
                           forKeyPath: @"framesPerSecond"
                           options: 0
                           context: NULL];
        else
            [captureReader removeObserver: self
                           forKeyPath: @"framesPerSecond"];
    }
    @catch(...) { }
}

- (void) start
{
    if(started)
        return;
    [super start];

    [session startRunning];
    captureReader.enableReader = YES;
}

- (void) stop
{
    if(!started)
        return;
    [super stop];

    captureReader.enableReader = NO;
    [session stopRunning];
}

- (void) flushCache
{
    [captureReader flushCache];
}

- (void) configureDevice
{
    if([device isFocusModeSupported: AVCaptureFocusModeContinuousAutoFocus])
        device.focusMode = AVCaptureFocusModeContinuousAutoFocus;
    if([device isTorchModeSupported: torchMode])
        device.torchMode = torchMode;
}

- (void) lockDevice
{
    if(!running || locked) {
        assert(0);
        return;
    }

    // lock device and set focus mode
    NSError *error = nil;
    if([device lockForConfiguration: &error]) {
        locked = YES;
        [self configureDevice];
    }
    else {
        zlog(@"failed to lock device: %@", error);
        // just keep trying
        [self performSelector: @selector(lockDevice)
              withObject: nil
              afterDelay: .5];
    }
}


// AVCaptureSession notifications

- (void) onVideoStart: (NSNotification*) note
{
    zlog(@"onVideoStart: running=%d %@", running, note);
    if(running)
        return;
    running = YES;
    locked = NO;

    [self lockDevice];

    if([readerDelegate respondsToSelector: @selector(readerViewDidStart:)])
        [readerDelegate readerViewDidStart: self];
}

- (void) onVideoStop: (NSNotification*) note
{
    zlog(@"onVideoStop: %@", note);
    if(!running)
        return;
    running = NO;

    if(locked)
        [device unlockForConfiguration];
    else
        [NSObject cancelPreviousPerformRequestsWithTarget: self
                  selector: @selector(lockDevice)
                  object: nil];
    locked = NO;

    if([readerDelegate respondsToSelector:
                           @selector(readerView:didStopWithError:)])
        [readerDelegate readerView: self
                        didStopWithError: nil];
}

- (void) onVideoError: (NSNotification*) note
{
    zlog(@"onVideoError: %@", note);
    if(running) {
        // FIXME does session always stop on error?
        running = started = NO;
        [device unlockForConfiguration];
    }
    NSError *err =
        [note.userInfo objectForKey: AVCaptureSessionErrorKey];

    if([readerDelegate respondsToSelector:
                           @selector(readerView:didStopWithError:)])
        [readerDelegate readerView: self
                        didStopWithError: err];
    else
        NSLog(@"ZBarReaderView: ERROR during capture: %@: %@",
              [err localizedDescription],
              [err localizedFailureReason]);
}

// NSKeyValueObserving

- (void) observeValueForKeyPath: (NSString*) path
                       ofObject: (id) obj
                         change: (NSDictionary*) info
                        context: (void*) ctx
{
    if(obj == captureReader &&
       [path isEqualToString: @"size"])
        // adjust preview to match image size
        [self setImageSize: captureReader.size];
    else if(obj == captureReader &&
       [path isEqualToString: @"framesPerSecond"])
        fpsLabel.text = [NSString stringWithFormat: @"%.2ffps ",
                                  captureReader.framesPerSecond];
}

// ZBarCaptureDelegate

- (void) captureReader: (ZBarCaptureReader*) reader
       didTrackSymbols: (ZBarSymbolSet*) syms
{
    [self didTrackSymbols: syms];
}

- (void)       captureReader: (ZBarCaptureReader*) reader
  didReadNewSymbolsFromImage: (ZBarImage*) zimg
{
    zlog(@"scanned %d symbols: %@", zimg.symbols.count, zimg);
    if(!readerDelegate)
        return;

    UIImageOrientation orient = [UIDevice currentDevice].orientation;
    if(!UIDeviceOrientationIsValidInterfaceOrientation(orient)) {
        orient = interfaceOrientation;
        if(orient == UIInterfaceOrientationLandscapeLeft)
            orient = UIDeviceOrientationLandscapeLeft;
        else if(orient == UIInterfaceOrientationLandscapeRight)
            orient = UIDeviceOrientationLandscapeRight;
    }
    switch(orient)
    {
    case UIDeviceOrientationPortraitUpsideDown:
        orient = UIImageOrientationLeft;
        break;
    case UIDeviceOrientationLandscapeLeft:
        orient = UIImageOrientationUp;
        break;
    case UIDeviceOrientationLandscapeRight:
        orient = UIImageOrientationDown;
        break;
    default:
        orient = UIImageOrientationRight;
        break;
    }

    UIImage *uiimg = [zimg UIImageWithOrientation: orient];
    [readerDelegate
        readerView: self
        didReadSymbols: zimg.symbols
        fromImage: uiimg];
}

@end