summaryrefslogtreecommitdiff
path: root/libcamera/webcam-tools.c
blob: 01a35017d72cc87d1f27e8f899798ce71f53f77b (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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
/*
 * from: https://github.com/bellbind/node-v4l2camera
 * capturing from UVC cam
 * requires: libjpeg-dev
 * build: gcc -std=c99 webcam-tools.c -ljpeg -o capture
 */

#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <asm/types.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/types.h>
#include <linux/videodev2.h>

#include <jpeglib.h>

#ifndef RESULT_PATH
#define RESULT_PATH "/tmp/result.jpg"
#define RESULT_YUYV_PATH "/tmp/result.yuyv"
#endif

//////////////// struct definition ////////////////////
typedef enum {
    CAMERA_INFO = 0,
    CAMERA_FAIL = 1,
    CAMERA_ERROR = 2,
} camera_log_t;

typedef void (*camera_log_func_t)(camera_log_t type, const char* msg, void* pointer);
typedef struct {
    void* pointer;
    camera_log_func_t log;
} camera_context_t;

typedef struct {
    uint8_t* start;
    size_t length;
} camera_buffer_t;

typedef struct {
    int fd;
    bool initialized;
    uint32_t width;
    uint32_t height;
    size_t buffer_count;
    camera_buffer_t* buffers;
    camera_buffer_t head;
    camera_context_t context;
} camera_t;

typedef struct {
    uint8_t description[32];
    uint32_t format;
    uint32_t width;
    uint32_t height;
    struct {
        uint32_t numerator;
        uint32_t denominator;
    } interval;
} camera_format_t;

typedef struct {
    size_t length;
    camera_format_t* head;
} camera_formats_t;


const char* type_names[] = {
    "INVALID",
    "INTEGER",
    "BOOLEAN",
    "MENU",
    "BUTTON",
    "INTEGER64",
    "CLASS",
    "STRING",
    "BITMASK",
    "INTEGER_MENU",
};
const char* bool_names[] = {
    "false",
    "true",
};

typedef enum {
    CAMERA_CTRL_INTEGER = 1,
    CAMERA_CTRL_BOOLEAN = 2,
    CAMERA_CTRL_MENU = 3,
    CAMERA_CTRL_BUTTON = 4,
    CAMERA_CTRL_INTEGER64 = 5,
    CAMERA_CTRL_CLASS = 6,
    CAMERA_CTRL_STRING = 7,
    CAMERA_CTRL_BITMASK = 8,
    CAMERA_CTRL_INTEGER_MENU = 9,
} camera_control_type_t;

typedef union {
    uint8_t name[32];
    int64_t value;
} camera_menu_t;

typedef struct {
    size_t length;
    camera_menu_t* head;
} camera_menus_t;

typedef struct {
    uint32_t id;
    uint8_t name[32];
    struct {
        unsigned disabled: 1;
        unsigned grabbed: 1;
        unsigned read_only: 1;
        unsigned update: 1;
        unsigned inactive: 1;
        unsigned slider: 1;
        unsigned write_only: 1;
        unsigned volatile_value: 1;
    } flags;
    camera_control_type_t type;
    int32_t max;
    int32_t min;
    int32_t step;
    int32_t default_value;
    camera_menus_t menus;
} camera_control_t;

typedef struct {
    size_t length;
    camera_control_t* head;
} camera_controls_t;

/////////////////////// utils functions definition
void quit(const char * msg) {
    fprintf(stderr, "[%s] %d: %s\n", msg, errno, strerror(errno));
    exit(EXIT_FAILURE);
}

static bool error(camera_t* camera, const char * msg) {
    camera->context.log(CAMERA_ERROR, msg, camera->context.pointer);
    return false;
}
static bool failure(camera_t* camera, const char * msg) {
    camera->context.log(CAMERA_FAIL, msg, camera->context.pointer);
    return false;
}

static void log_stderr(camera_log_t type, const char* msg, void* pointer) {
    (void) pointer;
    switch (type) {
        case CAMERA_ERROR:
            fprintf(stderr, "ERROR [%s] %d: %s\n", msg, errno, strerror(errno));
            return;
        case CAMERA_FAIL:
            fprintf(stderr, "FAIL [%s]\n", msg);
            return;
        case CAMERA_INFO:
            fprintf(stderr, "INFO [%s]\n", msg);
            return;
    }
}

int xioctl(int fd, int request, void* arg) {
    for (int i = 0; i < 100; i++) {
        int r = ioctl(fd, request, arg);
        if (r != -1 || errno != EINTR) return r;
    }
    return -1;
}
////////////////////////// camera related functions definition
static void free_buffers(camera_t* camera, size_t count) {
    for (size_t i = 0; i < count; i++) {
        munmap(camera->buffers[i].start, camera->buffers[i].length);
    }
    free(camera->buffers);
    camera->buffers = NULL;
    camera->buffer_count = 0;
}

camera_t* camera_open(const char * device, uint32_t width, uint32_t height) {
      int fd = open(device, O_RDWR | O_NONBLOCK, 0);
      if (fd == -1) quit("open");
      camera_t* camera = malloc(sizeof (camera_t));
      camera->fd = fd;
      camera->initialized = false;
      camera->width = width;
      camera->height = height;
      camera->buffer_count = 0;
      camera->buffers = NULL;
      camera->head.length = 0;
      camera->head.start = NULL;
      camera->context.pointer = NULL;
      camera->context.log = &log_stderr;
      return camera;
}

// check capacities and set the default crop rectangle
static bool camera_init(camera_t* camera) {
    struct v4l2_capability cap;
    if (xioctl(camera->fd, VIDIOC_QUERYCAP, &cap) == -1) return error(camera, "VIDIOC_QUERYCAP");
    if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) return failure(camera, "no capture");
    if (!(cap.capabilities & V4L2_CAP_STREAMING)) return failure(camera, "no streaming");

    struct v4l2_cropcap cropcap;
    memset(&cropcap, 0, sizeof cropcap);
    // Information about the video cropping and scaling abilities
    cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    if (xioctl(camera->fd, VIDIOC_CROPCAP, &cropcap) == 0) {
        struct v4l2_crop crop;
        crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        // defrect: Default cropping rectangle, it shall cover the “whole picture”.
        // Assuming pixel aspect 1/1 this could be for example a 640 × 480 rectangle for NTSC,
        // a 768 × 576 rectangle for PAL and SECAM centered over the active picture area.
        // The same co-ordinate system as for bounds is used.
        crop.c = cropcap.defrect;
        //  Set the current cropping rectangle
        if (xioctl(camera->fd, VIDIOC_S_CROP, &crop) == -1) {
            // cropping not supported
        }
    }

    camera->initialized = true;
    return true;
}


static void camera_buffer_finish(camera_t* camera) {
    free_buffers(camera, camera->buffer_count);
    free(camera->head.start);
    camera->head.length = 0;
    camera->head.start = NULL;
}

// release the buffer allocated, mmaped and requested
bool camera_stop(camera_t* camera) {
    enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    if (xioctl(camera->fd, VIDIOC_STREAMOFF, &type) == -1) return error(camera, "VIDIOC_STREAMOFF");
    camera_buffer_finish(camera);

    struct v4l2_requestbuffers req;
    memset(&req, 0, sizeof req);
    req.count = 0; /// set to 0 here to release the buffers
    req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    // Applications set this memory field to V4L2_MEMORY_MMAP, V4L2_MEMORY_DMABUF or V4L2_MEMORY_USERPTR. See v4l2_memory.
    // 3.6.5. enum v4l2_memory
    // V4L2_MEMORY_MMAP    1   The buffer is used for memory mapping I/O.
    // V4L2_MEMORY_USERPTR     2   The buffer is used for user pointer I/O.
    // V4L2_MEMORY_OVERLAY     3   [to do]
    // V4L2_MEMORY_DMABUF  4   The buffer is used for DMA shared buffer I/O.
    req.memory = V4L2_MEMORY_MMAP;
    // VIDIOC_REQBUFS - Initiate Memory Mapping, User Pointer I/O or DMA buffer I/O
    // The number of buffers requested or granted.
    if (xioctl(camera->fd, VIDIOC_REQBUFS, &req) == -1)  return error(camera, "VIDIOC_REQBUFS 0");
    return true;
}

bool camera_close(camera_t* camera) {
    if (camera->buffer_count > 0) {
        camera_stop(camera);
    }
    for (int i = 0; i < 10; i++) {
        if (close(camera->fd) != -1) break;
    }
    free(camera);
    return true;
}


//////////////////////////// definition for format
bool camera_format_get(camera_t* camera, camera_format_t* format) {
    // get the pixel format information
    struct v4l2_format vformat;
    memset(&vformat, 0, sizeof vformat);
    vformat.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    if (xioctl(camera->fd, VIDIOC_G_FMT, &vformat) == -1) {
        return error(camera, "VIDIOC_G_FMT");
    }

    format->format = vformat.fmt.pix.pixelformat;
    format->width = vformat.fmt.pix.width;
    format->height = vformat.fmt.pix.height;

    // get fps information
    struct v4l2_streamparm parm;
    memset(&parm, 0, sizeof parm);
    parm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    if (xioctl(camera->fd, VIDIOC_G_PARM, &parm) == -1) {
        return error(camera, "VIDIOC_G_PARM");
    }
    format->interval.numerator = parm.parm.capture.timeperframe.numerator;
    format->interval.denominator = parm.parm.capture.timeperframe.denominator;
    return true;
}

// get the current pixel format information and fps information
bool camera_fmt_config_get(camera_t* camera, camera_format_t* format) {
    return camera_format_get(camera, format);
}

uint32_t camera_format_id(const char* name) {
    //assert(strlen(name) == 4);
    return (uint32_t) name[0] | ((uint32_t) name[1] << 8) |
        ((uint32_t) name[2] << 16) | ((uint32_t) name[3] << 24);
}

void camera_format_name(uint32_t format_id, char* name) {
    name[0] = format_id & 0xff;
    name[1] = (format_id >> 8) & 0xff;
    name[2] = (format_id >> 16) & 0xff;
    name[3] = (format_id >> 24) & 0xff;
    name[4] = '\0';
}

camera_formats_t* camera_formats_new(const camera_t* camera) {
    camera_formats_t* ret = malloc(sizeof (camera_formats_t));
    ret->length = 0;
    ret->head = NULL;
    for (uint32_t i = 0; ; i++) {
        struct v4l2_fmtdesc fmt;
        memset(&fmt, 0, sizeof fmt);
        fmt.index = i;
        fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        // VIDIOC_ENUM_FMT - Enumerate image formats
        // On success 0 is returned, on error -1 and the errno variable is set appropriately. The generic error codes are described at the Generic Error Codes chapter.
        if (ioctl(camera->fd, VIDIOC_ENUM_FMT, &fmt) == -1) break;
        for (uint32_t j = 0; ; j++) {
            struct v4l2_frmsizeenum frmsize;
            memset(&frmsize, 0, sizeof frmsize);
            frmsize.index = j;
            frmsize.pixel_format = fmt.pixelformat;
            // VIDIOC_ENUM_FRAMESIZES - Enumerate frame sizes
            if (ioctl(camera->fd, VIDIOC_ENUM_FRAMESIZES, &frmsize) == -1) break;
            // V4L2_FRMSIZE_TYPE_DISCRETE    1   Discrete frame size.
            // V4L2_FRMSIZE_TYPE_CONTINUOUS    2   Continuous frame size.
            // V4L2_FRMSIZE_TYPE_STEPWISE  3   Step-wise defined frame size.
            if (frmsize.type == V4L2_FRMSIZE_TYPE_DISCRETE) {
                //printf("- w: %d, h: %d\n",
                //       frmsize.discrete.width, frmsize.discrete.height);
                for (uint32_t k = 0; ; k++) {
                    struct v4l2_frmivalenum frmival;
                    memset(&frmival, 0, sizeof frmival);
                    frmival.index = k;
                    frmival.pixel_format = fmt.pixelformat;
                    frmival.width = frmsize.discrete.width;
                    frmival.height = frmsize.discrete.height;
                    // VIDIOC_ENUM_FRAMEINTERVALS - Enumerate frame intervals
                    if (ioctl(camera->fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival) == -1) break;
                    // V4L2_FRMIVAL_TYPE_DISCRETE  1   Discrete frame interval.
                    // V4L2_FRMIVAL_TYPE_CONTINUOUS    2   Continuous frame interval.
                    // V4L2_FRMIVAL_TYPE_STEPWISE  3   Step-wise defined frame interval.
                    if (frmival.type == V4L2_FRMIVAL_TYPE_DISCRETE) {
                        //printf("  - fps: %d/%d\n",
                        //       frmival.discrete.denominator,frmival.discrete.numerator);
                        ret->head = realloc(ret->head, (ret->length + 1) * sizeof (camera_format_t));
                        memcpy(ret->head[ret->length].description, fmt.description, sizeof fmt.description);
                        ret->head[ret->length].format = fmt.pixelformat;
                        ret->head[ret->length].width = frmsize.discrete.width;
                        ret->head[ret->length].height = frmsize.discrete.height;
                        ret->head[ret->length].interval.numerator = frmival.discrete.numerator;
                        ret->head[ret->length].interval.denominator = frmival.discrete.denominator;
                        ret->length++;
                    } else {
                        //printf("  - fps: %d/%d-%d/%d\n",
                        //       frmival.stepwise.min.denominator,
                        //       frmival.stepwise.min.numerator,
                        //       frmival.stepwise.max.denominator,
                        //       frmival.stepwise.max.numerator);
                        // TBD: when stepwize
                    }
                    //printf("frmival.type=%d\n", frmival.type);
                }
            } else {
                //printf("- w: %d-%d, h: %d-%d\n",
                //       frmsize.stepwise.min_width, frmsize.stepwise.max_width,
                //      frmsize.stepwise.min_height, frmsize.stepwise.max_height);
                // TBD: when stepwize
            }
            //printf("frmsize.type=%d\n", frmsize.type);
        }

    }
    return ret;
}

void camera_formats_delete(camera_formats_t* formats) {
    free(formats->head);
    free(formats);
}

void print_formats_info(camera_t * camera) {
    puts("=================================");
    char name[5];
    camera_format_t format;
    camera_fmt_config_get(camera, &format);
    camera_format_name(format.format, name);
    puts("[current config]");
    printf("- [%s:%x] w: %d, h: %d, fps: %d/%d\n",
            name, format.format, format.width, format.height, format.interval.denominator, format.interval.numerator);

    puts("[available formats]");
    camera_formats_t* formats = camera_formats_new(camera);
    for (size_t i = 0; i < formats->length; i++) {
        camera_format_name(formats->head[i].format, name);
        printf("- [%s:%x:%s] w: %d, h: %d, fps: %d/%d\n",
            name, formats->head[i].format, formats->head[i].description, formats->head[i].width, formats->head[i].height,
            formats->head[i].interval.denominator,
            formats->head[i].interval.numerator);
    }
    puts("=================================");
    camera_formats_delete(formats);
}

////////////////// functions for controls //////////////////////////////////////////////////////////////////
static void  camera_menu_copy(camera_menu_t* menu, struct v4l2_querymenu* qmenu) {
    memcpy(menu->name, qmenu->name, sizeof qmenu->name);
}

#ifndef CAMERA_OLD_VIDEODEV2_H
static void camera_integer_menu_copy(camera_menu_t* menu, struct v4l2_querymenu* qmenu) {
    menu->value = qmenu->value;
}
#endif

static void camera_controls_menus(const camera_t* camera, camera_control_t* control) {
    void (*copy)(camera_menu_t*, struct v4l2_querymenu*) = &camera_menu_copy;
    switch (control->type) {
        case CAMERA_CTRL_MENU:
            break;
        #ifndef CAMERA_OLD_VIDEODEV2_H
        case CAMERA_CTRL_INTEGER_MENU:
            copy = &camera_integer_menu_copy;
            break;
        #endif
        default:
            control->menus.length = 0;
            control->menus.head = NULL;
        return;
    }
    control->menus.length = control->max + 1;
    control->menus.head = calloc(control->menus.length, sizeof (camera_menu_t));
    for (uint32_t mindex = 0; mindex < control->menus.length; mindex++) {
        struct v4l2_querymenu qmenu;
        memset(&qmenu, 0, sizeof qmenu);
        qmenu.id = control->id;
        qmenu.index = mindex;
        // VIDIOC_QUERYMENU - Enumerate menu control items
        if (ioctl(camera->fd, VIDIOC_QUERYMENU, &qmenu) == 0) {
            copy(&control->menus.head[mindex], &qmenu);
        }
    }
}

static camera_control_t* camera_controls_query(const camera_t* camera, camera_control_t* control_list) {
    camera_control_t* control_list_last = control_list;
    for (uint32_t cid = V4L2_CID_USER_BASE; cid < V4L2_CID_LASTP1; cid++) {
        struct v4l2_queryctrl qctrl;
        memset(&qctrl, 0, sizeof qctrl);
        qctrl.id = cid;
        // __u32    id  Identifies the control, set by the application. See Control IDs for predefined IDs.
        //              When the ID is ORed with V4L2_CTRL_FLAG_NEXT_CTRL the driver clears the flag and returns the first control with a higher ID.
        //              Drivers which do not support this flag yet always return an EINVAL error code.
        // VIDIOC_QUERYCTRL - VIDIOC_QUERY_EXT_CTRL - Enumerate controls
        if (ioctl(camera->fd, VIDIOC_QUERYCTRL, &qctrl) == -1) continue;
        camera_control_t* control = control_list_last++;
        control->id = qctrl.id;
        memcpy(control->name, qctrl.name, sizeof qctrl.name);
        // https://linuxtv.org/downloads/v4l-dvb-apis/uapi/v4l/vidioc-queryctrl.html#vidioc-queryctrl
        // V4L2_CTRL_FLAG_DISABLED  0x0001  This control is permanently disabled and should be ignored by the application. Any attempt to change the control will result in an EINVAL error code.
        // V4L2_CTRL_FLAG_GRABBED   0x0002  This control is temporarily unchangeable, for example because another application took over control of the respective resource.
        //                                  Such controls may be displayed specially in a user interface. Attempts to change the control may result in an EBUSY error code.
        // V4L2_CTRL_FLAG_READ_ONLY     0x0004  This control is permanently readable only. Any attempt to change the control will result in an EINVAL error code.
        // V4L2_CTRL_FLAG_UPDATE   0x0008  A hint that changing this control may affect the value of other controls within the same control class. Applications should update their user interface accordingly.
        // V4L2_CTRL_FLAG_INACTIVE  0x0010  This control is not applicable to the current configuration and should be displayed accordingly in a user interface.
        //                                  For example the flag may be set on a MPEG audio level 2 bitrate control when MPEG audio encoding level 1 was selected with another control.
        // V4L2_CTRL_FLAG_SLIDER    0x0020  A hint that this control is best represented as a slider-like element in a user interface.
        // V4L2_CTRL_FLAG_WRITE_ONLY    0x0040  This control is permanently writable only. Any attempt to read the control will result in an EACCES error code error code.
        //                                      This flag is typically present for relative controls or action controls where writing a value will cause the device to carry out a given action
        //                                      (e. g. motor control) but no meaningful value can be returned.
        // V4L2_CTRL_FLAG_VOLATILE  0x0080      This control is volatile, which means that the value of the control changes continuously.
        //                                      A typical example would be the current gain value if the device is in auto-gain mode
        //                                      In such a case the hardware calculates the gain value based on the lighting conditions which can change over time.

        // V4L2_CTRL_FLAG_HAS_PAYLOAD   0x0100  This control has a pointer type, so its value has to be accessed using one of the pointer fields of struct v4l2_ext_control.
        //                                      This flag is set for controls that are an array, string, or have a compound type.
        //                                      In all cases you have to set a pointer to memory containing the payload of the control.
        // V4L2_CTRL_FLAG_EXECUTE_ON_WRITE  0x0200   The value provided to the control will be propagated to the driver even if it remains constant.
        //                                           This is required when the control represents an action on the hardware. For example: clearing an error flag or triggering the flash.
        //                                           All the controls of the type V4L2_CTRL_TYPE_BUTTON have this flag set.
        // V4L2_CTRL_FLAG_MODIFY_LAYOUT     0x0400   Changing this control value may modify the layout of the buffer (for video devices) or the media bus format (for sub-devices).
        //                                           A typical example would be the V4L2_CID_ROTATE control.  Note that typically controls with this flag will also set the V4L2_CTRL_FLAG_GRABBED flag
        //                                           when buffers are allocated or streaming is in progress since most drivers do not support changing the format in that case.
        control->flags.disabled = (qctrl.flags & V4L2_CTRL_FLAG_DISABLED) != 0;
        control->flags.grabbed = (qctrl.flags & V4L2_CTRL_FLAG_GRABBED) != 0;
        control->flags.read_only = (qctrl.flags & V4L2_CTRL_FLAG_READ_ONLY) != 0;
        control->flags.update = (qctrl.flags & V4L2_CTRL_FLAG_UPDATE) != 0;
        control->flags.inactive = (qctrl.flags & V4L2_CTRL_FLAG_INACTIVE) != 0;
        control->flags.slider = (qctrl.flags & V4L2_CTRL_FLAG_SLIDER) != 0;
        control->flags.write_only = (qctrl.flags & V4L2_CTRL_FLAG_WRITE_ONLY) != 0;
        control->flags.volatile_value = (qctrl.flags & V4L2_CTRL_FLAG_VOLATILE) != 0;
        control->type = qctrl.type;
        control->max = qctrl.maximum;
        control->min = qctrl.minimum;
        control->step = qctrl.step;
        control->default_value = qctrl.default_value;
        camera_controls_menus(camera, control);
    }
    return control_list_last;
}

camera_controls_t* camera_controls_new(const camera_t* camera) {
    // https://linuxtv.org/downloads/v4l-dvb-apis/uapi/v4l/control.html
    // V4L2_CID_BASE  First predefined ID, equal to V4L2_CID_BRIGHTNESS.
    // V4L2_CID_USER_BASE Synonym of V4L2_CID_BASE.
    // 4L2_CID_LASTP1 End of the predefined control IDs (currently V4L2_CID_ALPHA_COMPONENT + 1).
    camera_control_t control_list[V4L2_CID_LASTP1 - V4L2_CID_USER_BASE];
    camera_control_t* control_list_last = camera_controls_query(camera, control_list);
    camera_controls_t* controls = malloc(sizeof (camera_controls_t));
    controls->length = control_list_last - control_list;
    controls->head = calloc(controls->length, sizeof (camera_control_t));
    for (size_t i = 0; i < controls->length; i++) {
        controls->head[i] = control_list[i];
    }
    return controls;
}

bool camera_control_get(camera_t* camera, uint32_t id, int32_t* value) {
    struct v4l2_control ctrl;
    ctrl.id = id;
    ctrl.value = 0;
    // VIDIOC_G_CTRL - VIDIOC_S_CTRL - Get or set the value of a control
    if (ioctl(camera->fd, VIDIOC_G_CTRL, &ctrl) == -1) return error(camera, "VIDIOC_G_CTRL");
    *value = ctrl.value;
    return true;
}

bool camera_control_set(camera_t* camera, uint32_t id, int32_t value) {
    struct v4l2_control ctrl;
    ctrl.id = id;
    ctrl.value = value;
    // VIDIOC_G_CTRL - VIDIOC_S_CTRL - Get or set the value of a control
    if (ioctl(camera->fd, VIDIOC_S_CTRL, &ctrl) == -1) return error(camera, "VIDIOC_S_CTRL");
    return true;
}

void camera_controls_delete(camera_controls_t* controls) {
    for (size_t i = 0; i < controls->length; i++) {
        free(controls->head[i].menus.head);
    }
    free(controls);
}

void print_controls_info(camera_t* camera) {
    puts("=================================");
    camera_controls_t* controls = camera_controls_new(camera);
    for (size_t i = 0; i < controls->length; i++) {
        camera_control_t* control = &controls->head[i];
        int32_t value = 0;
        camera_control_get(camera, control->id, &value);
        printf("[%s]\n", control->name);
        printf("- id: %d\n", control->id);
        printf("- type: %s\n", type_names[control->type]);
        printf("- value: %d\n", value);
        printf("- range: %d <- %d -> %d (step: %d)\n", control->min, control->default_value, control->max, control->step);
        switch (control->type) {
            case CAMERA_CTRL_MENU:
                puts("- menus");
                for (size_t j = 0; j < control->menus.length; j++) {
                    printf("    - %zu: [%s]\n", j, control->menus.head[j].name);
                }
                break;
            case CAMERA_CTRL_INTEGER_MENU:
                puts("- menus");
                for (size_t j = 0; j < control->menus.length; j++) {
                    printf("    - %zu: %"PRId64"\n", j, control->menus.head[j].value);
                }
                break;
            default: break;
        }
        puts("- flags");
        printf("    - disabled: %s\n", bool_names[control->flags.disabled]);
        printf("    - grabbed: %s\n", bool_names[control->flags.grabbed]);
        printf("    - read only: %s\n", bool_names[control->flags.read_only]);
        printf("    - update: %s\n", bool_names[control->flags.update]);
        printf("    - inactive: %s\n", bool_names[control->flags.inactive]);
        printf("    - slider: %s\n", bool_names[control->flags.slider]);
        printf("    - write_only: %s\n", bool_names[control->flags.write_only]);
        printf("    - volatile: %s\n", bool_names[control->flags.volatile_value]);
        puts("");
    }

    camera_controls_delete(controls);
    puts("=================================");
}
/////////////////// definition for capture  //////////////////////////
static bool camera_format_set(camera_t* camera, const camera_format_t* format) {
    if (format->width > 0 && format->height > 0) {
        uint32_t pixformat = format->format ? format->format : V4L2_PIX_FMT_YUYV;
        struct v4l2_format vformat;
        memset(&vformat, 0, sizeof vformat);
        vformat.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        vformat.fmt.pix.width = format->width;
        vformat.fmt.pix.height = format->height;
        vformat.fmt.pix.pixelformat = pixformat;
        vformat.fmt.pix.field = V4L2_FIELD_NONE;
        // VIDIOC_G_FMT - VIDIOC_S_FMT - VIDIOC_TRY_FMT - Get or set the data format, try a format
        if (xioctl(camera->fd, VIDIOC_S_FMT, &vformat) == -1) return error(camera, "VIDIOC_S_FMT");
    }
    if (format->interval.numerator != 0 && format->interval.denominator != 0) {
        struct v4l2_streamparm parm;
        memset(&parm, 0, sizeof parm);
        parm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        parm.parm.capture.timeperframe.numerator = format->interval.numerator;
        parm.parm.capture.timeperframe.denominator = format->interval.denominator;
        if (xioctl(camera->fd, VIDIOC_S_PARM, &parm) == -1) return error(camera, "VIDIOC_S_PARM");
    }
    return true;
}

static bool camera_load_fmt_settings(camera_t* camera) {
    struct v4l2_format format;
    memset(&format, 0, sizeof format);
    format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    if (xioctl(camera->fd, VIDIOC_G_FMT, &format) == -1) return error(camera, "VIDIOC_G_FMT");
    camera->width = format.fmt.pix.width;
    camera->height = format.fmt.pix.height;
    return true;
}

static bool camera_buffer_prepare(camera_t* camera) {
    if (camera->buffer_count > 0) {
        if (!camera_stop(camera)) return false;
    }
    if (!camera->initialized) {
        if (!camera_init(camera)) return false;
    }

    struct v4l2_requestbuffers req;
    memset(&req, 0, sizeof req);
    req.count = 4; /// TODO: <============why set 4 here?
    req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    // Applications set this memory field to V4L2_MEMORY_MMAP, V4L2_MEMORY_DMABUF or V4L2_MEMORY_USERPTR. See v4l2_memory.
    // 3.6.5. enum v4l2_memory
    // V4L2_MEMORY_MMAP    1   The buffer is used for memory mapping I/O.
    // V4L2_MEMORY_USERPTR     2   The buffer is used for user pointer I/O.
    // V4L2_MEMORY_OVERLAY     3   [to do]
    // V4L2_MEMORY_DMABUF  4   The buffer is used for DMA shared buffer I/O.
    req.memory = V4L2_MEMORY_MMAP;
    // VIDIOC_REQBUFS - Initiate Memory Mapping, User Pointer I/O or DMA buffer I/O
    // The number of buffers requested or granted.
    if (xioctl(camera->fd, VIDIOC_REQBUFS, &req) == -1) return error(camera, "VIDIOC_REQBUFS");
    camera->buffer_count = req.count;
    camera->buffers = calloc(req.count, sizeof (camera_buffer_t));

    size_t buf_max = 0;
    for (size_t i = 0; i < camera->buffer_count; i++) {
        struct v4l2_buffer buf;
        memset(&buf, 0, sizeof buf);
        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        buf.memory = V4L2_MEMORY_MMAP;
        buf.index = i;
        // VIDIOC_QUERYBUF — Query the status of a buffer
        if (xioctl(camera->fd, VIDIOC_QUERYBUF, &buf) == -1) {
            free_buffers(camera, i);
            return error(camera, "VIDIOC_QUERYBUF");
        }
        if (buf.length > buf_max) buf_max = buf.length;
        camera->buffers[i].length = buf.length;
        camera->buffers[i].start =  mmap(NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, camera->fd, buf.m.offset);
        if (camera->buffers[i].start == MAP_FAILED) {
            free_buffers(camera, i);
            return error(camera, "mmap");
        }
    }
    camera->head.start = calloc(buf_max, sizeof (uint8_t));
    return true;
}

static bool camera_load(camera_t* camera) {
    if (!camera->initialized) {
        if (!camera_init(camera)) return false;
    }
    if (camera->buffer_count == 0) {
        if (!camera_load_fmt_settings(camera)) return false;
        if (!camera_buffer_prepare(camera)) return false;
    }
    return true;
}

// queue the buffer and VIDIOC_STREAMON,
bool camera_start(camera_t* camera) {
    if (!camera_load(camera)) return false;

    // Applications set this memory field to V4L2_MEMORY_MMAP, V4L2_MEMORY_DMABUF or V4L2_MEMORY_USERPTR. See v4l2_memory.
    // 3.6.5. enum v4l2_memory
    // V4L2_MEMORY_MMAP    1   The buffer is used for memory mapping I/O.
    // V4L2_MEMORY_USERPTR     2   The buffer is used for user pointer I/O.
    // V4L2_MEMORY_OVERLAY     3   [to do]
    // V4L2_MEMORY_DMABUF  4   The buffer is used for DMA shared buffer I/O.
    for (size_t i = 0; i < camera->buffer_count; i++) {
        struct v4l2_buffer buf;
        memset(&buf, 0, sizeof buf);
        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        buf.memory = V4L2_MEMORY_MMAP;
        buf.index = i;
        // make the webcam/or mmapped ram?) buffer in queue to cache picture content
        if (xioctl(camera->fd, VIDIOC_QBUF, &buf) == -1) return error(camera, "VIDIOC_QBUF");
    }

    enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    if (xioctl(camera->fd, VIDIOC_STREAMON, &type) == -1) return error(camera, "VIDIOC_STREAMON");
    return true;
}

bool camera_fmt_config_set(camera_t* camera, const camera_format_t* format) {
    return camera_format_set(camera, format) && camera_load_fmt_settings(camera);
}

static inline int minmax(int min, int v, int max) {
    return (v < min) ? min : (max < v) ? max : v;
}
static inline uint8_t yuv2r(int y, int u, int v) {
    int c = y-16, d = u - 128, e = v - 128;
    // https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/1071301e-74a2-4de4-be72-81c34604cde9/program-to-translate-yuyv-to-rgbrgb?forum=windowsdirectshowdevelopment
    int r = (298 * c           + 409 * e + 128) >> 8;
    // linaro webcam
    // int r = (1.164 * c +       1.596 * e      );
    // int r = (y + 359 * v) >> 8;
    return minmax(0, r, 255);
}
static inline uint8_t yuv2g(int y, int u, int v) {
    int c = y - 16, d = u - 128, e = v - 128;
    int g = (298 * c   - 100 * d   - 208 * e + 128) >> 8;
    // int g = (1.164 * c - 0.391 * d - 0.813 * e    )
    // int g = (y + 88 * v - 183 * u) >> 8;
    return minmax(0, g, 255);
}
static inline uint8_t yuv2b(int y, int u, int v) {
    int c = y - 16, d = u - 128, e = v - 128;
    int b = (298 * c  + 516 * d           + 128) >> 8;
    //int b = (1.164 * c + 2.018 * d );
    //int b = (y + 454 * u) >> 8;
    return minmax(0, b, 255);
}

unsigned char* yuyv2rgb(const unsigned char* yuyv, uint32_t width, uint32_t height) {
    unsigned char* rgb = calloc(width * height * 3, sizeof (unsigned char));
    for (long i = 0; i < height; i++) {
        for ( long j = 0; j < width; j += 2) {
            long indexPixel = i * width + j;
            long indexYUYV = indexPixel * 2, indexRGB = indexPixel * 3;
            unsigned char y0 = yuyv[indexYUYV + 0] ;
            unsigned char u = yuyv[indexYUYV + 1];
            unsigned char y1 = yuyv[indexYUYV + 2];
            unsigned char v = yuyv[indexYUYV + 3];
            rgb[indexRGB + 0] = yuv2r(y0, u, v);
            rgb[indexRGB + 1] = yuv2g(y0, u, v);
            rgb[indexRGB + 2] = yuv2b(y0, u, v);
            rgb[indexRGB + 3] = yuv2r(y1, u, v);
            rgb[indexRGB + 4] = yuv2g(y1, u, v);
            rgb[indexRGB + 5] = yuv2b(y1, u, v);
        }
    }
    return rgb;
}

//[[capturing]
bool camera_capture(camera_t* camera) {
    struct v4l2_buffer buf;
    memset(&buf, 0, sizeof buf);
    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    buf.memory = V4L2_MEMORY_MMAP;
    if (xioctl(camera->fd, VIDIOC_DQBUF, &buf) == -1) return false;
    // copy content in buffer to the head
    memcpy(camera->head.start, camera->buffers[buf.index].start, buf.bytesused);
    camera->head.length = buf.bytesused;
    fprintf(stdout, "%s: after call VIDIOC_DQBUF buf.index=%d buf.bytesused=%d, camera->width=%d, camera->height=%d\n", __FUNCTION__, buf.index, buf.bytesused,  camera->width, camera->height);
    // after VIDIOC_DQBUF, call VIDIOC_QBUF to re-use  that buf
    if (xioctl(camera->fd, VIDIOC_QBUF, &buf) == -1) return false;
    return true;
}

bool camera_frame(camera_t* camera, struct timeval timeout) {
    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(camera->fd, &fds);
    int r = select(camera->fd + 1, &fds, 0, 0, &timeout);
    if (r == -1){
        fprintf(stdout, "%s: error occurred when call select: %s\n", __FUNCTION__, strerror(errno));
        if(EINTR == errno) {
            return true;
        }
        exit(EXIT_FAILURE);
    } else if (r == 0) {
        fprintf(stdout, "%s: select timeout\n", __FUNCTION__);
        return false;
    }
    return camera_capture(camera);
}

void jpeg(FILE* dest, uint8_t* rgb, uint32_t width, uint32_t height, int quality) {
    JSAMPARRAY image = calloc(height, sizeof (JSAMPROW));
    for (size_t i = 0; i < height; i++) {
        image[i] = calloc(width * 3, sizeof (JSAMPLE));
        for (size_t j = 0; j < width; j++) {
            image[i][j * 3 + 0] = rgb[(i * width + j) * 3 + 0];
            image[i][j * 3 + 1] = rgb[(i * width + j) * 3 + 1];
            image[i][j * 3 + 2] = rgb[(i * width + j) * 3 + 2];
        }
    }

    struct jpeg_compress_struct compress;
    struct jpeg_error_mgr error;
    compress.err = jpeg_std_error(&error);
    jpeg_create_compress(&compress);
    jpeg_stdio_dest(&compress, dest);
    compress.image_width = width;
    compress.image_height = height;
    compress.input_components = 3;
    compress.in_color_space = JCS_RGB;
    jpeg_set_defaults(&compress);
    jpeg_set_quality(&compress, quality, TRUE);
    jpeg_start_compress(&compress, TRUE);
    jpeg_write_scanlines(&compress, image, height);
    jpeg_finish_compress(&compress);
    jpeg_destroy_compress(&compress);

    for (size_t i = 0; i < height; i++) {
        free(image[i]);
    }
    free(image);
}

void capture_image(camera_t* camera, char* output){
    camera_format_t fmt_config = {"", 0, camera->width, camera->height, {0, 0}};
    if (!camera_fmt_config_set(camera, &fmt_config)) return;

    char name[5];
    if (!camera_fmt_config_get(camera, &fmt_config)) return;
    camera_format_name(fmt_config.format, name);
    if ( (strcmp(name, "YUYV") == 0) || (strcmp(name, "MJPG") == 0) ) {
        fprintf(stdout, "default camera format is [%s]\n", name);

        printf("- [%s:%x] w: %d, h: %d, fps: %d/%d\n",
            name, fmt_config.format, fmt_config.width, fmt_config.height, fmt_config.interval.denominator, fmt_config.interval.numerator);
    } else {
        fprintf(stderr, "camera format [%s] is not supported strcmp(name, \"YUYV\")=%d\n", name, strcmp(name, "YUYV"));
        return;
    }

    // camera_buffer_prepare(camera);

    if (!camera_start(camera)){
        fprintf(stderr, "failed to start camera\n");
        return;
    }
    struct timeval timeout;
    timeout.tv_sec = 10;
    timeout.tv_usec = 0;
    /* skip 5 frames for booting a cam */
    for (int i = 0; i < 5; i++) {
        camera_frame(camera, timeout);
    }
    camera_frame(camera, timeout);

    FILE* out = fopen(output, "w");
    if (strcmp(name, "YUYV") == 0) {
        unsigned char* rgb = yuyv2rgb(camera->head.start, camera->width, camera->height);
        jpeg(out, rgb, camera->width, camera->height, 100);
        free(rgb);

        FILE* out2 = fopen(RESULT_YUYV_PATH, "w");
        fwrite(camera->head.start, camera->head.length, 1, out2);
        fclose(out2);
    } else if (strcmp(name, "MJPG") == 0 ) {
        errno = 0;
        fwrite(camera->head.start, camera->head.length, 1, out);
        if (errno != 0){
            fprintf(stderr, "Failed to write to file %s \n", output);
        }
    }
    fclose(out);

    fprintf(stdout, "Result file is saved here: %s\n", output);

    camera_stop(camera);
}

/////////////////// definition for main //////////////////////////
int main(int argc, char* argv[]) {
/*
    char* f_yuyv = argc > 1 ? argv[1] : RESULT_YUYV_PATH;
    char* f_jpg = argc > 2 ? argv[2] : RESULT_PATH;
    uint32_t width = argc > 3 ? atoi(argv[3]) : 640;
    uint32_t height = argc > 4 ? atoi(argv[4]) : 480;

    unsigned int size = 614400;
    char buffer[size];
    FILE* fp = fopen(f_yuyv, "r");
    fread(buffer, size, 1, fp);
    fclose(fp);

    FILE* out = fopen(f_jpg, "w");
    unsigned char* rgb = yuyv2rgb(buffer, width, height);
    jpeg(out, rgb, width, height, 100);
    free(rgb);
*/
//*
    char* device = argc > 1 ? argv[1] : "/dev/video0";
    uint32_t width = argc > 2 ? atoi(argv[2]) : 640;
    uint32_t height = argc > 3 ? atoi(argv[3]) : 480;
    char* output = argc > 4 ? argv[4] : RESULT_PATH;
    camera_t* camera = camera_open(device, width, height);

    print_formats_info(camera);

    //print_controls_info(camera);

    capture_image(camera, output);

    camera_close(camera);

//*/
    return 0;
}