aboutsummaryrefslogtreecommitdiff
path: root/circuitpython/lib/quirc/demo/camera.c
blob: 8e8de6bef3afecfe9b335c4bdda4a88c9c9e437b (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
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
/* quirc -- QR-code recognition library
 * Copyright (C) 2010-2014 Daniel Beer <dlbeer@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <stdint.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>
#ifdef __OpenBSD__
#include <sys/videoio.h>
#else
#include <linux/videodev2.h>
#endif
#include "camera.h"

/************************************************************************
 * Fraction arithmetic
 */

static int gcd(int a, int b)
{
	if (a < 0)
		a = -a;
	if (b < 0)
		b = -b;

	for (;;) {
		if (a < b) {
			const int t = a;

			a = b;
			b = t;
		}

		if (!b)
			break;

		a %= b;
	}

	return a;
}

static void frac_reduce(const struct v4l2_fract *f, struct v4l2_fract *g)
{
	const int x = gcd(f->numerator, f->denominator);
	int n = f->numerator;
	int d = f->denominator;

	if (d < 0) {
		n = -n;
		d = -d;
	}

	g->numerator = n / x;
	g->denominator = d / x;
}

static void frac_add(const struct v4l2_fract *a, const struct v4l2_fract *b,
		     struct v4l2_fract *r)
{
	r->numerator = a->numerator * b->denominator +
		       b->numerator * b->denominator;
	r->denominator = a->denominator * b->denominator;

	frac_reduce(r, r);
}

static void frac_sub(const struct v4l2_fract *a, const struct v4l2_fract *b,
		     struct v4l2_fract *r)
{
	r->numerator = a->numerator * b->denominator -
		       b->numerator * b->denominator;
	r->denominator = a->denominator * b->denominator;

	frac_reduce(r, r);
}

static int frac_cmp(const struct v4l2_fract *a, const struct v4l2_fract *b)
{
	return a->numerator * b->denominator - b->numerator * b->denominator;
}

static void frac_mul(const struct v4l2_fract *a, const struct v4l2_fract *b,
		     struct v4l2_fract *r)
{
	r->numerator = a->numerator * b->numerator;
	r->denominator = a->denominator * b->denominator;

	frac_reduce(r, r);
}

static void frac_div(const struct v4l2_fract *a, const struct v4l2_fract *b,
		     struct v4l2_fract *r)
{
	r->numerator = a->numerator * b->denominator;
	r->denominator = a->denominator * b->numerator;

	frac_reduce(r, r);
}

static int frac_cmp_ref(const struct v4l2_fract *ref,
			const struct v4l2_fract *a,
			const struct v4l2_fract *b)
{
	struct v4l2_fract da;
	struct v4l2_fract db;

	frac_sub(a, ref, &da);
	frac_sub(b, ref, &db);

	if (da.numerator < 0)
		da.numerator = -da.numerator;
	if (db.numerator < 0)
		db.numerator = -db.numerator;

	return frac_cmp(&da, &db);
}

/************************************************************************
 * Parameter searching and choosing
 */

static camera_format_t map_fmt(uint32_t pf)
{
	if (pf == V4L2_PIX_FMT_YUYV)
		return CAMERA_FORMAT_YUYV;

	if (pf == V4L2_PIX_FMT_MJPEG)
		return CAMERA_FORMAT_MJPEG;

	return CAMERA_FORMAT_UNKNOWN;
}

static int find_best_format(int fd, uint32_t *fmt_ret)
{
	struct v4l2_fmtdesc best;
	int i = 1;

	memset(&best, 0, sizeof(best));
	best.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	best.index = 0;

	if (ioctl(fd, VIDIOC_ENUM_FMT, &best) < 0)
		return -1;

	for (;;) {
		struct v4l2_fmtdesc f;

		memset(&f, 0, sizeof(f));
		f.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
		f.index = ++i;

		if (ioctl(fd, VIDIOC_ENUM_FMT, &f) < 0)
			break;

		if (map_fmt(f.pixelformat) > map_fmt(best.pixelformat))
			memcpy(&best, &f, sizeof(best));
	}

	if (fmt_ret)
		*fmt_ret = best.pixelformat;

	return 0;
}

static int step_to_discrete(int min, int max, int step, int target)
{
	int offset;

	if (target < min)
		return min;

	if (target > max)
		return max;

	offset = (target - min) % step;
	if ((offset * 2 > step) && (target + step <= max))
		target += step;

	return target - offset;
}

static int score_discrete(const struct v4l2_frmsizeenum *f, int w, int h)
{
	const int dw = f->discrete.width - w;
	const int dh = f->discrete.height - h;

	return dw * dw + dh * dh;
}

static int find_best_size(int fd, uint32_t pixel_format,
			  int target_w, int target_h,
			  int *ret_w, int *ret_h)
{
	struct v4l2_frmsizeenum best;
	int i = 1;

	memset(&best, 0, sizeof(best));
	best.index = 0;
	best.pixel_format = pixel_format;

	if (ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &best) < 0)
		return -1;

	if (best.type != V4L2_FRMSIZE_TYPE_DISCRETE) {
		*ret_w = step_to_discrete(best.stepwise.min_width,
					  best.stepwise.max_width,
					  best.stepwise.step_width,
					  target_w);
		*ret_h = step_to_discrete(best.stepwise.min_height,
					  best.stepwise.max_height,
					  best.stepwise.step_height,
					  target_h);
		return 0;
	}

	for (;;) {
		struct v4l2_frmsizeenum f;

		memset(&f, 0, sizeof(f));
		f.index = ++i;
		f.pixel_format = pixel_format;

		if (ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &f) < 0)
			break;

		if (score_discrete(&f, target_w, target_h) <
		    score_discrete(&best, target_w, target_h))
			memcpy(&best, &f, sizeof(best));
	}

	*ret_w = best.discrete.width;
	*ret_h = best.discrete.height;

	return 0;
}

static int find_best_rate(int fd, uint32_t pixel_format,
			  int w, int h, int target_n, int target_d,
			  int *ret_n, int *ret_d)
{
	const struct v4l2_fract target = {
		.numerator = target_n,
		.denominator = target_d
	};
	struct v4l2_frmivalenum best;
	int i = 1;

	memset(&best, 0, sizeof(best));
	best.index = 0;
	best.pixel_format = pixel_format;
	best.width = w;
	best.height = h;

	if (ioctl(fd, VIDIOC_ENUM_FRAMEINTERVALS, &best) < 0)
		return -1;

	if (best.type != V4L2_FRMIVAL_TYPE_DISCRETE) {
		struct v4l2_fract t;

		if (frac_cmp(&target, &best.stepwise.min) < 0) {
			*ret_n = best.stepwise.min.numerator;
			*ret_d = best.stepwise.min.denominator;
		}

		if (frac_cmp(&target, &best.stepwise.max) > 0) {
			*ret_n = best.stepwise.max.numerator;
			*ret_d = best.stepwise.max.denominator;
		}

		frac_sub(&target, &best.stepwise.min, &t);
		frac_div(&t, &best.stepwise.step, &t);
		if (t.numerator * 2 >= t.denominator)
			t.numerator += t.denominator;
		t.numerator /= t.denominator;
		t.denominator = 1;
		frac_mul(&t, &best.stepwise.step, &t);
		frac_add(&t, &best.stepwise.max, &t);

		if (frac_cmp(&t, &best.stepwise.max) > 0) {
			*ret_n = best.stepwise.max.numerator;
			*ret_d = best.stepwise.max.denominator;
		} else {
			*ret_n = t.numerator;
			*ret_d = t.denominator;
		}

		return 0;
	}

	for (;;) {
		struct v4l2_frmivalenum f;

		memset(&f, 0, sizeof(f));
		f.index = ++i;
		f.pixel_format = pixel_format;
		f.width = w;
		f.height = h;

		if (ioctl(fd, VIDIOC_ENUM_FRAMEINTERVALS, &f) < 0)
			break;

		if (frac_cmp_ref(&target, &f.discrete, &best.discrete) < 0)
			memcpy(&best, &f, sizeof(best));
	}

	*ret_n = best.discrete.numerator;
	*ret_d = best.discrete.denominator;

	return 0;
}

/************************************************************************
 * Public interface
 */

void camera_init(struct camera *c)
{
	c->fd = -1;
	c->buf_count = 0;
	c->s_on = 0;
}

void camera_destroy(struct camera *c)
{
	camera_close(c);
}

int camera_open(struct camera *c, const char *path,
		int target_w, int target_h,
		int tr_n, int tr_d)
{
	struct v4l2_format fmt;
	struct v4l2_streamparm parm;
	uint32_t pf;
	int w, h;
	int n, d;

	if (c->fd >= 0)
		camera_close(c);

	/* Open device and get basic properties */
	c->fd = open(path, O_RDWR);
	if (c->fd < 0)
		return -1;

	/* Find a pixel format from the list */
	if (find_best_format(c->fd, &pf) < 0)
		goto fail;

	/* Find a frame size */
	if (find_best_size(c->fd, pf, target_w, target_h, &w, &h) < 0)
		goto fail;

	/* Find a frame rate */
	if (find_best_rate(c->fd, pf, w, h, tr_n, tr_d, &n, &d) < 0)
		goto fail;

	/* Set format */
	memset(&fmt, 0, sizeof(fmt));
	fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	fmt.fmt.pix.width = w;
	fmt.fmt.pix.height = h;
	fmt.fmt.pix.pixelformat = pf;
	if (ioctl(c->fd, VIDIOC_S_FMT, &fmt) < 0)
		goto fail;

	memset(&fmt, 0, sizeof(fmt));
	fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	if (ioctl(c->fd, VIDIOC_G_FMT, &fmt) < 0)
		goto fail;

	/* Set frame interval */
	memset(&parm, 0, sizeof(parm));
	parm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	parm.parm.capture.timeperframe.numerator = n;
	parm.parm.capture.timeperframe.denominator = d;
	if (ioctl(c->fd, VIDIOC_S_PARM, &parm) < 0)
		goto fail;

	memset(&parm, 0, sizeof(parm));
	parm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	if (ioctl(c->fd, VIDIOC_G_PARM, &parm) < 0)
		goto fail;

	c->parms.format = map_fmt(fmt.fmt.pix.pixelformat);
	c->parms.width = fmt.fmt.pix.width;
	c->parms.height = fmt.fmt.pix.height;
	c->parms.pitch_bytes = fmt.fmt.pix.bytesperline;
	c->parms.interval_n = parm.parm.capture.timeperframe.numerator;
	c->parms.interval_d = parm.parm.capture.timeperframe.denominator;

	return 0;

fail:
	{
		const int e = errno;

		close(c->fd);
		c->fd = -1;
		errno = e;
	}

	return -1;
}

void camera_close(struct camera *c)
{
	camera_off(c);
	camera_unmap(c);

	if (c->fd < 0)
		return;

	close(c->fd);
	c->fd = -1;
}

int camera_map(struct camera *c, int buf_count)
{
	struct v4l2_requestbuffers reqbuf;
	int count;
	int i;

	if (buf_count > CAMERA_MAX_BUFFERS)
		buf_count = CAMERA_MAX_BUFFERS;

	if (buf_count <= 0) {
		errno = EINVAL;
		return -1;
	}

	if (c->fd < 0) {
		errno = EBADF;
		return -1;
	}

	if (c->buf_count)
		camera_unmap(c);

	memset(&reqbuf, 0, sizeof(reqbuf));
	reqbuf.count = buf_count;
	reqbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	reqbuf.memory = V4L2_MEMORY_MMAP;

	if (ioctl(c->fd, VIDIOC_REQBUFS, &reqbuf) < 0)
		return -1;

	count = reqbuf.count;
	if (count > CAMERA_MAX_BUFFERS)
		count = CAMERA_MAX_BUFFERS;

	/* Query all buffers */
	for (i = 0; i < count; i++) {
		struct v4l2_buffer buf;
		struct camera_buffer *cb = &c->buf_desc[i];

		memset(&buf, 0, sizeof(buf));
		buf.index = i;
		buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
		buf.memory = V4L2_MEMORY_MMAP;
		if (ioctl(c->fd, VIDIOC_QUERYBUF, &buf) < 0)
			return -1;

		cb->offset = buf.m.offset;
		cb->size = buf.length;
		cb->addr = mmap(NULL, cb->size, PROT_READ,
			MAP_SHARED, c->fd, cb->offset);

		if (cb->addr == MAP_FAILED) {
			const int save = errno;

			i--;
			while (i >= 0) {
				cb = &c->buf_desc[i--];
				munmap(cb->addr, cb->size);
			}

			errno = save;
			return -1;
		}
	}

	c->buf_count = count;
	return 0;
}

void camera_unmap(struct camera *c)
{
	int i;

	for (i = 0; i < c->buf_count; i++) {
		struct camera_buffer *cb = &c->buf_desc[i];

		munmap(cb->addr, cb->size);
	}

	c->buf_count = 0;
}

int camera_on(struct camera *c)
{
	int type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

	if (c->s_on)
		return 0;

	if (c->fd < 0) {
		errno = EBADF;
		return -1;
	}

	if (ioctl(c->fd, VIDIOC_STREAMON, &type) < 0)
		return -1;

	c->s_on = 1;
	c->s_qc = 0;
	c->s_qhead = 0;
	return 0;
}

void camera_off(struct camera *c)
{
	int type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

	if (!c->s_on)
		return;

	ioctl(c->fd, VIDIOC_STREAMOFF, &type);
	c->s_on = 0;
}

int camera_enqueue_all(struct camera *c)
{
	while (c->s_qc < c->buf_count) {
		struct v4l2_buffer buf;

		memset(&buf, 0, sizeof(buf));
		buf.index = (c->s_qc + c->s_qhead) % c->buf_count;
		buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
		buf.memory = V4L2_MEMORY_MMAP;

		if (ioctl(c->fd, VIDIOC_QBUF, &buf) < 0)
			return -1;

		c->s_qc++;
	}

	return 0;
}

int camera_dequeue_one(struct camera *c)
{
	struct v4l2_buffer buf;

	if (!c->s_qc) {
		errno = EINVAL;
		return -1;
	}

	memset(&buf, 0, sizeof(buf));
	buf.memory = V4L2_MEMORY_MMAP;
	buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

	if (ioctl(c->fd, VIDIOC_DQBUF, &buf) < 0)
		return -1;

	c->s_qc--;
	if (++c->s_qhead >= c->buf_count)
		c->s_qhead = 0;

	return 0;
}